使用PySide2设置后台线程的困难

时间:2019-10-06 17:20:53

标签: python qthread pyside2

我一直在使用PySide2在Python中创建GUI,我真的很喜欢它。

我现在正在设法绕过线程,但是我正在挣扎。

我有一个带有日志和一个切换按钮的GUI,用于模拟开关。我希望每次按下按钮时都会向日志中添加一条新消息。我知道,只需将按钮连接到函数上,就可以在不使用线程的情况下实现此目的,但是我正在尝试学习如何使用线程。

这是我的代码:

# libs
import sys, time
from PySide2 import QtCore, QtWidgets
from PySide2.QtCore import QObject, Qt
from PySide2.QtWidgets import QMainWindow, QWidget, QVBoxLayout

# initial values
previnput1A = 0
input1A = 0

# ~ MAIN CODE ~
class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        self.centralWidget = QtWidgets.QWidget(MainWindow)
        self.gridLayout = QtWidgets.QGridLayout(self.centralWidget)
        MainWindow.setCentralWidget(self.centralWidget)

        # log
        self.log = QtWidgets.QPlainTextEdit()
        self.log.setReadOnly(True)
        self.log_layout = QtWidgets.QVBoxLayout()
        self.log.setLayout(self.log_layout)
        self.gridLayout.addWidget(self.log, 2, 1)

        # buttons
        # simulated switch
        self.switch = QtWidgets.QPushButton()
        self.switch.setText('simulated switch')
        self.switch.setCheckable(True)
        self.switch.setObjectName('switch')
        self.gridLayout.addWidget(self.switch, 1, 1)

class MainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self):
        Ui_MainWindow.__init__(self)
        QMainWindow.__init__(self)

        self.setGeometry(50, 50, 480, 300)

        # initialize UI
        self.setupUi(self)
        # buttons
        self.switch.clicked.connect(self.switchPress)

        self.get_thread = updateThread()
        self.get_thread.start()

    def switchPress(self):
        global input1A
        if self.switch.isChecked():
            msg = 'switch 1A pressed'
            input1A = 1
        else:
            msg = 'switch 1A released'
            input1A = 0
        self.log.appendPlainText(msg)

    def reeval(self):
        msg = 'reeval'
        self.log.appendPlainText(msg)

# thread to allow updating once gui has been created
class updateThread(QtCore.QThread):
    def __init__(self):
        QtCore.QThread.__init__(self)

    def __del__(self):
        self.wait()

    def run(self):
        global previnput1A, input1A
        while True:
            time.sleep(0.01)
            if input1A != previnput1A:
                previnput1A = input1A
                main_window.reeval()

if __name__ == "__main__":
    # app initialisation
    app = QtWidgets.QApplication(sys.argv)
    # call the widget
    main_window = MainWindow()
    main_window.show()
    sys.exit(app.exec_())

我的问题是,当按下按钮时,UI退出。

有人能指出我在哪里做错了正确的方向吗? 谢谢

0 个答案:

没有答案