PyDesigner PyQt5 MouseEvent不起作用setMouseTracking(True)

时间:2018-11-28 03:32:10

标签: python python-3.x pyqt pyqt5 qt-designer

如何让MouseEvent工作?

我尝试打印鼠标跟踪以标记x,y坐标,但始终失败。我已经在使用setMouseTracking(True),从QtDesigner ui生成到py。

下面的代码:

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(640, 480)
        Form.setMouseTracking(True)
        self.label = QtWidgets.QLabel(Form)
        self.label.setGeometry(QtCore.QRect(270, 190, 58, 15))
        self.label.setObjectName("label")
        self.label.setMouseTracking(True)
        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "Form"))
        self.label.setText(_translate("Form", "TextLabel"))

    def mouseMoveEvent(self, e):

        x = e.x()
        y = e.y()

        text = "x: {0},  y: {1}".format(x, y)
        self.label.setText(text)
if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    Form = QtWidgets.QWidget()
    ui = Ui_Form()
    ui.setupUi(Form)
    Form.show()
    sys.exit(app.exec_())

1 个答案:

答案 0 :(得分:1)

Ui_Form不是窗口小部件,因此它将没有mouseMoveEvent方法,因为the PyQt docs指出您必须创建一个继承相应窗口小部件的类,在本例中为QWidget,并使用Qt Designer提供的接口:

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(640, 480)
        Form.setMouseTracking(True)
        self.label = QtWidgets.QLabel(Form)
        self.label.setGeometry(QtCore.QRect(270, 190, 58, 15))
        self.label.setObjectName("label")
        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "Form"))
        self.label.setText(_translate("Form", "TextLabel"))

class Form(QtWidgets.QWidget, Ui_Form):
    def __init__(self, parent=None):
        super(Form, self).__init__(parent)
        self.setupUi(self)
        self.setMouseTracking(True)

    def mouseMoveEvent(self, e):
        text = "x: {0},  y: {1}".format(e.x(), e.y())
        self.label.setText(text)
        self.label.adjustSize()
        super(Form, self).mouseMoveEvent(e)

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    w = Form()
    w.show()
    sys.exit(app.exec_())