I tried to design a pyqt gui in when I press "x" will stop run
function a
counter , what should i do ?
I only know to use the following code
def closeEvent(self,event):
pass
Logic Code
from PyQt5 import QtWidgets, QtGui, QtCore
from PyQt5.QtCore import *
import sys
import time
from GUI import Ui_MainWindow
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.thread = MyThread(self)
self.thread.trigger.connect(self.textBrowser)
self.thread.start()
def textBrowser(self,a):
self.ui.textBrowser_4.clear()
self.ui.textBrowser_4.append(str(a))
def closeEvent(self,event):
pass
class MyThread(QThread):
trigger = pyqtSignal(str)
def run(self):
a = 0
while True:
a = a 1
self.trigger.emit(str(a))
time.sleep(1)
if __name__ == "__main__":
app = QtWidgets.QApplication([])
MainWindow = MainWindow()
MainWindow.show()
sys.exit(app.exec_())
GUI Code
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(944, 587)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.label_2 = QtWidgets.QLabel(self.centralwidget)
self.label_2.setGeometry(QtCore.QRect(30, 310, 181, 41))
self.label_2.setObjectName("label_2")
self.label_4 = QtWidgets.QLabel(self.centralwidget)
self.label_4.setGeometry(QtCore.QRect(30, 20, 141, 21))
self.label_4.setObjectName("label_4")
self.textBrowser_4 = QtWidgets.QTextBrowser(self.centralwidget)
self.textBrowser_4.setGeometry(QtCore.QRect(230, 300, 241, 61))
self.textBrowser_4.setObjectName("textBrowser_4")
MainWindow.setCentralWidget(self.centralwidget)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.label_2.setText(_translate("MainWindow", "counter"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
CodePudding user response:
Add an initiator and an is_running variable in your Thread class like so :
def __init__(self):
self.is_running = True
Then make your loop depend on the truthness of this new variable :
def run(self):
a = 0
while self.is_running:
... your logic here
And finally when you want to exit in closeEvent() :
self.thread.is_running = False
Cheers
CodePudding user response:
If you just want to know how to stop a while loop, i think you want "break". Example code:
i = 0
while True:
print(i)
i = 1
if i > 10:
break
which prints:
0
1
2
3
4
5
6
7
8
9
10