PyQt:如何从QThread获取UI数据

时间:2017-02-13 09:35:21

标签: python multithreading pyqt signals-slots qthread

我有以下代码,但它抱怨我无法从我的线程访问UI数据。在下面的示例代码中,我可以访问ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1); 值的最佳方式是什么,以便我的线程可以运行?

userInputString是一个PyQt QLineEdit。

  

QObject :: setParent:无法设置父级,新父级位于不同的线程中   QPixmap:在GUI线程之外使用pixmaps是不安全的   QWidget :: repaint:检测到递归重绘

self.nameField

1 个答案:

答案 0 :(得分:2)

不确定它是否是你需要的,但这是一个使用Qt5的工作QThread例子

import time
import sys
from PyQt5 import QtWidgets, QtGui, QtCore

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.worker_thread = WorkerThread()
        self.worker_thread.job_done.connect(self.on_job_done)
        self.create_ui()

    def create_ui(self):
        self.button = QtWidgets.QPushButton('Test', self)
        self.button.clicked.connect(self.start_thread)
        layout = QtWidgets.QVBoxLayout(self)
        layout.addWidget(self.button)

    def start_thread(self):
        self.worker_thread.gui_text = self.button.text()
        self.worker_thread.start()

    def on_job_done(self, generated_str):
        print("Generated string : ", generated_str)
        self.button.setText(generated_str)


class WorkerThread(QtCore.QThread):

    job_done = QtCore.pyqtSignal('QString')

    def __init__(self, parent=None):
        super(WorkerThread, self).__init__(parent)
        self.gui_text = None

    def do_work(self):

        for i in range(0, 1000):
            print(self.gui_text)
            self.job_done.emit(self.gui_text + str(i))
            time.sleep(0.5)

    def run(self):
        self.do_work()


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    test = MainWindow()
    test.show()
    app.exec_()