我希望我的pyqt应用程序在我按下“取消”按钮时停止。 例如,这个应用程序应该从两个表循环特性。我可以设置一个触发器,它将始终根据按下“取消”按钮来检查其状态(真/假)。但是有没有办法设置全局触发器来停止任何代码位置的应用程序进程?在
import time
import sys
from PyQt5 import QtCore, QtWidgets, QtGui
from PyQt5.QtWidgets import (QApplication, QWidget, QToolTip, QPushButton, QMessageBox, QTreeWidget, QTreeWidgetItem, QProgressBar, QLabel)
class Pio(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.launch = False
self.pbar = QProgressBar(self)
self.pbar.setGeometry(20,20,400,50)
self.okButton = QPushButton(self)
self.okButton.setGeometry(80, 20, 100, 50)
self.okButton.move(20, 80)
self.okButton.setText('launch')
self.cncl = QPushButton(self)
self.cncl.setGeometry(300, 20, 100, 50)
self.cncl.move(320, 80)
self.cncl.setText('cancel')
self.okButton.clicked.connect(self.start_loop)
self.cncl.clicked.connect(self.break_loop)
self.show()
def start_loop(self):
if not self.launch:
self.launch = True
print ('started!')
self.loop_numbers()
def break_loop(self):
print ('canceled!')
if self.launch:
print ('work in progress....')
self.launch = False
def loop_numbers(self):
print ('running')
'action #1 that takes a lot of time '
'action #2 that also takes a lot of time'
for n in range(101):
if self.launch:
self.pbar.setValue(n)
time.sleep(0.01)
QtCore.QCoreApplication.processEvents()
for n in range(11):
if self.launch:
self.pbar.setValue(n*10)
time.sleep(0.05)
QtCore.QCoreApplication.processEvents()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Pio()
sys.exit(app.exec_())
如果我将self.launch
移到loop_numbers()
的开头,一旦循环启动,它将在整个进程中运行。在
当最后一个窗口关闭时,应用程序将自动关闭,因此您可以尝试将
QWidget
更改为QMainWindow
,只需从取消按钮调用close。在相关问题 更多 >
编程相关推荐