How do I react when I raise the mouse cursor on Pyside2 PushButton?

Asked 2 years ago, Updated 2 years ago, 104 views

Title I want to put functions such as changing the text or image of the button when I put the mouse cursor over the PushButton widget on Pyside2, but I don't know how to do it.

python pyside2

2022-09-21 12:14

1 Answers

Please keep that in mind.

import sys
from PySide2 import QtCore
from PySide2.QtWidgets import QApplication, QWidget, QVBoxLayout, QPushButton, QMessageBox

class MyForm(QWidget):
    def __init__(self,parent=None):
        QWidget.__init__(self,parent)
        self.setWindowTitle('Button Demo')

        self.button = QPushButton('Ok',self)
        self.button.clicked.connect(self.do_clicked)
        self.button.installEventFilter(self)
        mainlayout = QVBoxLayout()
        mainlayout.addWidget(self.button)
        self.setLayout(mainlayout)

    def eventFilter(self, obj, event):
        if obj == self.button and event.type() == QtCore.QEvent.HoverEnter:
            self.button.setText("Ko")
        elif obj == self.button and event.type() == QtCore.QEvent.HoverLeave:
            self.button.setText("Ok")
        return super(MyForm, self).eventFilter(obj, event)

    def do_clicked(self):
        buttonReply = QMessageBox.question(self, 'title', "message", QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
        if buttonReply == QMessageBox.Yes:
            print('Yes clicked.')
        else:
            print('No clicked.')

if __name__ == '__main__':
    app = QApplication(sys.argv)
    form = MyForm()
    form.show()
    app.exec_()


2022-09-21 12:14

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.