我是Python和Qt的新手。当前,我正在尝试为更大的应用程序构建UI,但是我遇到了有关信号和插槽的问题。

这是我的代码:

from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import QObject, pyqtSlot
import sys


class Ui_configDialog(QtWidgets.QDialog):
    def __init__(self):
        super(Ui_configDialog, self).__init__()

        self.setupUi()

    def setupUi(self):
        self.setObjectName("configDialog")
        self.setWindowModality(QtCore.Qt.WindowModal)
        self.resize(425, 380)

        row1 = DataRow(self)

        self.show()


class DataRow:
    def __init__(self, dialog):
        rect = QtCore.QRect(10, 40, 91, 30)

        self.text_fRep = QtWidgets.QSpinBox(dialog)
        self.text_fRep.setGeometry(rect.translated(100, 0))
        self.connect_signal()

    @pyqtSlot(int)
    def fRep_changed(self, value):
        print(value)

    def connect_signal(self):
        self.text_fRep.valueChanged.connect(self.fRep_changed)


if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    dialog = Ui_configDialog()
    sys.exit(app.exec_())


我想要实现的是,每当QSpinBox对象的值更改时,都会调用插槽fRep_changed。但是使用此代码,我收到一个编译错误:

QObject::connect: Cannot connect QSpinBox::valueChanged(int) to (null)::fRep_changed(int)
TypeError: connect() failed between valueChanged(int) and fRep_changed()


我看不到,为什么我不能将信号连接到插槽。

我还删除了@pyqtSlot(int)。应用程序启动,但是更改值后什么也没有发生。

提前谢谢你的帮助!

最佳答案

您的代码有2个错误,第一个错误是插槽仅在从QObject继承的类中实现,因此最容易的事情是您的类从QObject继承。在进行了上一次更改之后,您将看到第二秒钟,即使您更改了QSpinBox的值,也永远不会调用该插槽,这是因为收集器删除了row1DataRow对象>类,解决方案很简单,您只需要通过self使row成为类的成员,即将row1换成self.row1

class Ui_configDialog(QtWidgets.QDialog):
    def __init__(self):
        super(Ui_configDialog, self).__init__()

        self.setupUi()

    def setupUi(self):
        self.setObjectName("configDialog")
        self.setWindowModality(QtCore.Qt.WindowModal)
        self.resize(425, 380)

        self.row1 = DataRow(self)

        self.show()


class DataRow(QObject):
    def __init__(self, dialog, parent=None):
        QObject.__init__(self, parent)

        rect = QtCore.QRect(10, 40, 91, 30)

        self.text_fRep = QtWidgets.QSpinBox(dialog)
        self.text_fRep.setGeometry(rect.translated(100, 0))
        self.connect_signal()

    @pyqtSlot(int)
    def fRep_changed(self, value):
        print(value)

    def connect_signal(self):
        self.text_fRep.valueChanged.connect(self.fRep_changed)

09-25 15:32