簡體   English   中英

QThread導致整個程序在pyqt5中休眠

[英]QThread causing entire program to sleep in pyqt5

這是我嘗試對QThreads進行子類化並在程序中使用它的第一次嘗試,但是我感到有些奇怪。 我不確定我的構造函數是錯誤的還是類似的東西,但是基本上,當我運行我的QThread時,整個程序都會在QThread休眠時休眠(而不僅僅是線程)

例如,提供的代碼將在3秒鍾后打印“ Hello there”(這是QThread應該休眠的時間)

如何修復代碼,以便在程序運行時讓線程在后台運行

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()

使用startrun

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

    print("Hello there")

由於run是線程的起點 (如果您想重復使用不在線程中的代碼,則該起點存在),

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()

希望它能對您有所幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM