PyQt5:将信号从工作线程连接到主窗口



我正在使用 PyQt5 用于 GUI 应用程序,其中按下按钮后运行带有 while 循环的 QThread。我想在我的主窗口的状态栏中的QThread类中输出一些有关进程的信息。因此,我尝试使用插槽和信号来连接两个线程。但是,状态栏不会更新。

我知道window.print_status("Executed loop")在这个最小的示例中工作,但不是好的做法,并且在较大的应用程序中会崩溃。

如何将线程发出的信号正确连接到主窗口?

我附上一个最小的例子:

from PyQt5.QtWidgets import QMainWindow, QApplication
from PyQt5 import uic, QtCore, QtGui, QtWidgets
from os import mkdir,path
from time import sleep,strftime,localtime
from shutil import copytree
ui_path = path.dirname(path.abspath(__file__))
Ui_MainWindow, QtBaseClass = uic.loadUiType(path.join(ui_path, "minimal.ui"))
class Communication(QtCore.QObject):
signal_str = QtCore.pyqtSignal(str)
class MyApp(QMainWindow):
def __init__(self):
super(MyApp, self).__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.ui.pushButton.clicked.connect(self.button_clicked)
def button_clicked(self):
print("Start pressed")
self.Thread = WorkingThread()
self.Thread.start()

@QtCore.pyqtSlot(str)    
def print_status(self,messagestring):
print("Executing print_status with", messagestring)
self.ui.statusbar.showMessage(messagestring)
class WorkingThread(QtCore.QThread):
def __init__(self):
QtCore.QThread.__init__(self)
self.signals = Communication()
self.signals.signal_str.connect(window.print_status)
def __del__(self):
self.wait()
def run(self):
#do something
self.run = 1
try:
while self.run==1:
#do some stuff in a loop
#window.print_status("Executed loop")
self.signals.print_status.emit("Hello World.")
#sleep for a while and repeat
sleep(30)
except:
return
if __name__ == '__main__':
#sys.stdout = open(path.join(ui_path, "logFile.txt"), 'w')
app = QApplication(sys.argv)
window = MyApp()
window.show()
sys.exit(app.exec_())

这是我的 ui 文件:

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>MainWindow</class>
<widget class="QMainWindow" name="MainWindow">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>800</width>
<height>600</height>
</rect>
</property>
<property name="windowTitle">
<string>MainWindow</string>
</property>
<widget class="QWidget" name="centralwidget">
<widget class="QLabel" name="label">
<property name="geometry">
<rect>
<x>146</x>
<y>176</y>
<width>281</width>
<height>81</height>
</rect>
</property>
<property name="text">
<string>Minimal Example</string>
</property>
</widget>
<widget class="QPushButton" name="pushButton">
<property name="geometry">
<rect>
<x>300</x>
<y>170</y>
<width>311</width>
<height>101</height>
</rect>
</property>
<property name="text">
<string>PushButton</string>
</property>
</widget>
</widget>
<widget class="QMenuBar" name="menubar">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>800</width>
<height>22</height>
</rect>
</property>
</widget>
<widget class="QStatusBar" name="statusbar"/>
</widget>
<resources/>
<connections/>
</ui>

我想我发现了我的错误:

而不是使用:

self.signals.print_status.emit("Hello World.")

它应该是:

self.signals.signal_str.emit("Hello World.")

最新更新