PyQt信号和插槽:"新风格"发射?

时间:2017-02-24 11:25:45

标签: python-3.x pyqt qt-signals

我试图围绕如何正确使用PyQt5Python3的线程和信号,但不知何故无法理解这一切是如何运作的。我在这里找到了一个示例代码,现在正尝试在PyQt5中使用它。

这是gui文件ui.py

from PyQt5 import QtCore, QtWidgets

class Ui_Win(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(416, 292)
        self.centralWidget = QtWidgets.QWidget(MainWindow)
        self.centralWidget.setObjectName("centralWidget")
        MainWindow.setCentralWidget(self.centralWidget)

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_Win()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

这是主要的脚本test_slotting.py

from ui import Ui_Win
from PyQt5 import QtGui, QtCore, QtWidgets
from PyQt5.QtCore import pyqtSlot
import time

class GenericThread(QtCore.QThread):
    def __init__(self, parent=None):
        QtCore.QThread.__init__(self, parent)

    def __del__(self):
        self.quit()
        self.wait()

    def run(self):
        #Do all your heavy processing here
        #I'll just wait for 2 seconds
        time.sleep(2)
        self.emit(QtCore.pyqtSignal('itemSelectionChanged()'))
        return


class MainUI(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        QtWidgets.QMainWindow.__init__(self)
        self.ui = Ui_Win()
        self.ui.setupUi(self)
        self.ui.List1 = QtWidgets.QListWidget(self)
        self.ui.List2 = QtWidgets.QListWidget(self)

        hbox = QtWidgets.QHBoxLayout()
        hbox.addStretch(1)
        hbox.addWidget(self.ui.List1)
        hbox.addWidget(self.ui.List2)

        self.ui.centralWidget.setLayout(hbox)

        self.ui.List1.addItems(['alpha','beta','gamma','delta','epsilon'])
        self.ui.List2.addItems(['Item1','Item2'])

        self.ui.List1.itemSelectionChanged.connect(self.start_heavy_processing_thread)

    @pyqtSlot()
    def start_heavy_processing_thread(self):
        genericThread = GenericThread(self)
        # self.connect(genericThread, QtCore.SIGNAL("itemSelectionChanged()"), self.fill_List2 )
        genericThread.itemSelectionChanged.connect(self.fill_List2)
        genericThread.start()

    def fill_List2(self):
        self.ui.List2.clear()
        list1SelectedItem = str(self.ui.List1.currentItem().text())
        self.ui.List2.addItem(list1SelectedItem)

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

从最初的代码示例中,我不得不改变旧样式"

self.connect(genericThread, QtCore.SIGNAL("itemSelectionChanged()"), self.fill_List2 )

到"新风格"

self.ui.List1.itemSelectionChanged.connect(self.start_heavy_processing_thread)

但是,现在我得到以下AttributeError: 'GenericThread' object has no attribute 'itemSelectionChanged'。我想test_slotting.py中的这一行仍然是#34;旧式":

self.emit(QtCore.pyqtSignal('itemSelectionChanged()'))

但它的新款式是什么?任何帮助将不胜感激......

2 个答案:

答案 0 :(得分:2)

错误是非常期待的。您的GenericThread没有名为itemSelectionChanged()的信号,因此您无法将不存在的信号连接到插槽。此信号属于您的QListWidget,而不属于您的GenericThread

在您决定创建自定义帐号之前,我建议您详细了解QThread的工作原理。特别是如果你的那个帖子与插槽和信号一起工作,你实际上进行了重复处理",由于QThread的性质,你会被搞砸 - 只有run()里面的内容{{} 1}}实际上在一个单独的线程内运行。其余的(插槽,信号,类成员等)属于您从中生成自己的QThread的线程 - 在您的情况下,这是主线程。

我上传了一个使用PyQt和线程here的示例,您可以在其中查看通常如何完成的事情。我也在那里使用新风格。

关于新风格的简短说明:

我们假设你有一个QWidget派生类,其中QPushButton名为button,而do_work()就是你想要触发的时段self.button.clicked.connect(self.do_work) | | | | | | | | | signal of emitter | slot of receiver | | signal emitter signal receiver 单击按钮。要建立此连接,您必须执行以下操作:

self

在这种情况下,self.do_work是接收者,因此我们使用do_work来说明广告符self属于clicked,并且信号button所在的位置fill_List2()<html> <head> <style> @font-face { font-family: 'NotoEmoji-Regular'; src: url('NotoEmoji-Regular.ttf') format('truetype'); unicode-range: U+1F300-1F5FF, U+1F600-1F64F, U+1F680-1F6FF, U+2600-26FF; } body{ font-family: "NotoEmoji-Regular", "Roboto", sans-serif !important; color: red; } </style> </head> <body> Chain <br/> ◉ Dot <br/> Group <br/> Person <br/> Folder <br/> Eye <br/> Scroll <br/> Tools <br/> </body> </html> 发出的1}}必须降落。

PS:我注意到你试图使用装饰器,但只是部分地这样做。如果您想使用这些(我强烈建议您这样做),您需要在TreeSet<Product> orderList = new TreeSet<>(new Comparator<Product>() { @Override public int compare(Product prod1, Product prod2) { return prod1.getNumber().compareTo(prod2.getNumber()); } }); orderList.addAll(result); 函数中添加一个插槽装饰器。

答案 1 :(得分:0)

更新后的代码

<强> ui.py:

 from PyQt5 import QtWidgets


    class Ui_Win(object):
        def setupUi(self, MainWindow):
            MainWindow.setObjectName("MainWindow")
            MainWindow.resize(416, 292)
            self.centralWidget = QtWidgets.QWidget(MainWindow)
            self.centralWidget.setObjectName("centralWidget")
            MainWindow.setCentralWidget(self.centralWidget)

            self.List1 = QtWidgets.QListWidget()
            self.List2 = QtWidgets.QListWidget()

            self.hbox = QtWidgets.QHBoxLayout()
            self.hbox.addStretch(1)
            self.hbox.addWidget(self.List1)
            self.hbox.addWidget(self.List2)

            self.centralWidget.setLayout(self.hbox)


    if __name__ == "__main__":
        import sys
        app = QtWidgets.QApplication(sys.argv)
        MainWindow = QtWidgets.QMainWindow()
        ui = Ui_Win()
        ui.setupUi(MainWindow)
        MainWindow.show()
        sys.exit(app.exec_())

<强> test_slotting.py:

from ui import Ui_Win
from PyQt5 import QtWidgets, QtCore
from PyQt5.QtCore import pyqtSlot, pyqtSignal, QObject

class Trigger(QObject):  # --> or QtCore.QThread? What's the difference?
    trigger = pyqtSignal()

    def connect_emit(self, pressed_item, list_to_update):
        self.pressed_item = pressed_item  # --> this kind of looks ugly to me... hmmm...
        self.list_to_update = list_to_update  # --> this kind of looks ugly to me... hmmm...

        self.trigger.connect(self.run)
        self.trigger.emit()

    def run(self):
        self.list_to_update.clear()
        self.list_to_update.addItem(self.pressed_item)


class MainUI(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        QtWidgets.QMainWindow.__init__(self)
        self.ui = Ui_Win()
        self.ui.setupUi(self)

        self.ui.List1.addItems(['alpha', 'beta', 'gamma', 'delta', 'epsilon'])
        self.ui.List2.addItems(['Item1', 'Item2'])

        self.ui.List1.itemSelectionChanged.connect(self.start_heavy_processing_thread)

    @pyqtSlot()  # --> what does this actually do? code also works without it...
    def start_heavy_processing_thread(self):
        genericThread = Trigger()
        myitem = [str(x.text()) for x in self.ui.List1.selectedItems()][0]
        mylist = self.ui.List2
        genericThread.connect_emit(myitem, mylist)


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