13

好的,几乎每个教程/可理解的人类语言文档都是针对 PyQt4 的。但是,PyQt5 改变了整个“连接按钮到插槽”的工作方式,我仍然不知道该怎么做。

我在 QtDesigner 中做了一个快速的 gui,我有一个 QPushButton 和一个标签。当我单击按钮时,我希望标签上的文本发生变化。在 QtDesigner 中的 C++ 中,很容易将两者联系起来。但是我必须全部用python编写。

我将 .ui 文件与 pyuic5 转换为 .py 文件。在那里,在 Ui_MainWindow 类中,我可以看到 setupUi 方法,该方法初始化 self.button 如下

self.testButton = QtWidgets.QPushButton(self.centralWidget)
self.testButton.setObjectName("newGame")

然后,在方法结束时,

QtCore.QMetaObject.connectSlotsByName(MainWindow)

被称为,但是,老实说,我无法弄清楚它的作用以及它在哪里连接。

在 Main 类中,继承自 QMainWindow,我编写了以下方法

@pyqtSlot(name='change')
def change_text(self):
    self.ui.testLabel.setText("Button Clicked!")

而且我不知道如何将按钮信号连接到该插槽。在 pyqt4 中,我可以通过 button.clicked.connect(self.change_text) 手动设置它,但正如我发现的那样,PyQt5 已经过时并放弃了这种简单的设置。

拜托,有人可以帮我解决这个问题吗?

4

1 回答 1

24

I don't know where you got the idea that "PyQt5 changed how the whole 'connect button to a slot' works", but it is completely and utterly wrong. There have been no such changes, as can be readily seen from the official PyQt documentation:

But even without reading any documentation, it's easy enough to test for yourself. For example, in the following script, just switch comments on the first two lines, and it will run just the same:

# from PyQt5.QtWidgets import (
from PyQt4.QtGui import (
    QApplication, QWidget, QVBoxLayout, QPushButton, QLabel,
    )

class Window(QWidget):
    def __init__(self):
        super(Window, self).__init__()
        self.button = QPushButton('Test', self)
        self.label = QLabel(self)
        self.button.clicked.connect(self.handleButton)
        layout = QVBoxLayout(self)
        layout.addWidget(self.label)
        layout.addWidget(self.button)

    def handleButton(self):
        self.label.setText('Button Clicked!')

if __name__ == '__main__':

    import sys
    app = QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())

As for the other points: at your current state of knowledge, I would say you can safely ignore connectSlotsByName and pyqtSlot. Although they have their uses (see the above docs for details), there's very rarely any real need to use them in 95% of applications.

For your specific case, the syntax is simply:

    self.testButton.clicked.connect(self.change_text)
    ...

def change_text(self):
    self.ui.testLabel.setText("Button Clicked!")
于 2013-11-14T00:15:29.193 回答