QThread导致整个程序在pyqt5中休眠

QThread causing entire program to sleep in pyqt5

这是我第一次尝试继承 QThreads 并在程序中使用它,但我遇到了一些奇怪的事情。我不确定我的构造函数是否错误或类似的东西,但基本上当我 运行 我的 QThread 整个程序在 QThread 休眠时休眠(不仅仅是线程)

例如,提供的代码将在 3 秒后打印 "Hello there",这是 QThread 应该休眠的时间

如何修复我的代码,以便在程序 运行ning

时我的线程 运行ning 可以在后台运行
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import QThread, pyqtSignal
import time

class MyThread(QThread):
    def __init__(self):
        QThread.__init__(self)

    def __del__(self):
        self.wait()

    def run(self):
        self.sleep(3)
        print("Slept for 3 seconds")


def main():
    qThread = MyThread()
    qThread.run()

    print("Hello there")

main()

使用 start 而不是 run:

def main():
    qThread = MyThread()
    qThread.start()

    print("Hello there")

因为 run 是线程的 starting point(如果您想重用不在线程中的代码,它就存在),

start是线程本身启动的方法,所以会依次调用run

为了完成 ptolemy0 的回答,我可以与您分享我用来在 Qt 上练习的代码:

from PyQt5.QtCore import QThread
from PyQt5.QtWidgets import  QWidget, QApplication
import sys, time

class MyThread(QThread):
    def __init__(self, parent=None):
        super(MyThread, self).__init__(parent)

    def __del__(self):
        self.wait()

    def run(self):
        while True:
            self.sleep(3)
            print("Slept for 3 seconds")

class Main(QWidget):

    def __init__(self, parent=None):

        super(Main,self).__init__(parent)

        qThread = MyThread()
        qThread.start()

        i=0
        while True:

            print(i)
            i+=1
            time.sleep(1)



def main():

    app = QApplication(sys.argv)
    example = Main()

    print("Hello there")
    sys.exit(app.exec())

main()

希望对您有所帮助!