Python PyQt5从不同线程调用类
我正在使用Python3和pyqt5制作一个简单的计时器,一旦完成就会发出警报。对于计时器,我刚刚创建了一个循环,它可以休眠一秒钟。据我所知,我需要使用线程来使用循环,并让该循环更新UI,而不会冻结,直到循环完成 我遇到的问题是,一旦循环完成,我希望我的函数调用另一个线程中的类。我尝试过使用QThread和threading,但似乎无法解决如何使循环从不同的线程调用类Python PyQt5从不同线程调用类,python,python-3.x,python-multithreading,pyqt5,Python,Python 3.x,Python Multithreading,Pyqt5,我正在使用Python3和pyqt5制作一个简单的计时器,一旦完成就会发出警报。对于计时器,我刚刚创建了一个循环,它可以休眠一秒钟。据我所知,我需要使用线程来使用循环,并让该循环更新UI,而不会冻结,直到循环完成 我遇到的问题是,一旦循环完成,我希望我的函数调用另一个线程中的类。我尝试过使用QThread和threading,但似乎无法解决如何使循环从不同的线程调用类 import sys, time, threading from PyQt5 import QtCore, QtGui, QtW
import sys, time, threading
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtMultimedia import QSound
# setting up the UI
class Ui_Form(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.setupUi(self)
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(303, 227)
self.setWorkTxt = QtWidgets.QPlainTextEdit(Form)
self.setWorkTxt.setGeometry(QtCore.QRect(10, 150, 141, 31))
self.setWorkTxt.setObjectName("setWorkTxt")
self.pushButton = QtWidgets.QPushButton(Form)
self.pushButton.setGeometry(QtCore.QRect(10, 190, 141, 27))
self.pushButton.setObjectName("pushButton")
self.countDownTimer = QtWidgets.QLCDNumber(Form)
self.countDownTimer.setGeometry(QtCore.QRect(13, 52, 281, 91))
self.countDownTimer.setProperty("intValue", 0)
self.countDownTimer.setObjectName("countDownTimer")
self.retranslateUi(Form)
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "Timer"))
self.setWorkTxt.setPlainText(_translate("Form", "enter time"))
self.pushButton.setText(_translate("Form", "Start"))
self.pushButton.clicked.connect(self.start)
# this function creates a new thread and starts the timer
def start(self):
t = threading.Thread(target=self.timer, args=( ))
t.start()
# timer function
def timer(self):
num = int(self.setWorkTxt.toPlainText())
for i in range (1, num + 1):
self.countDownTimer.display(i)
time.sleep(1)
audio.alarm() # this is where I want to call the class from the parent thread
# This is the alarm that I want to sound once the timer is finished
class audio(QSound):
def alarm():
QSound.play("alarm.wav")
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
ex = Ui_Form()
ex.show()
sys.exit(app.exec_())
我对python和Qt有点陌生,所以如果我把一些术语弄错了或遗漏了一些简单的内容,我深表歉意。如果需要时间,请使用PyQt5.QtCode.QTimer。但是,如果您的目标是学习多线程和Qt,那么您还需要了解更多。谢谢Barry Scott。我现在了解到,线程的复杂性比我最初想象的要大得多。如果需要时间,请使用PyQt5.QtCode.QTimer。但是,如果您的目标是学习多线程和Qt,那么您还需要了解更多。谢谢Barry Scott。我现在了解到,线程比我最初想象的要复杂得多。