Implement A Cancel Button With Qt In Python
This question is probably dumb, but to give some background: I have been given a bunch of code of a software whose GUI is written in Qt, and I have been told that I should improve
Solution 1:
This is a short example of how you can implement it. Please let me know if you want me to add notes.
from PyQt5 import QtWidgets, QtCore
class WorkerThread(QtCore.QThread):
is_active = True
def run(self):
while self.is_active:
print("Processing...")
self.sleep(1)
class Window(QtWidgets.QWidget):
def __init__(self, parent=None):
super(Window, self).__init__(parent)
self.start_button = QtWidgets.QPushButton("Start")
self.cancel_button = QtWidgets.QPushButton("Cancel")
self.start_button.clicked.connect(self.start)
self.cancel_button.clicked.connect(self.stop)
laytout = QtWidgets.QVBoxLayout()
laytout.addWidget(self.start_button)
laytout.addWidget(self.cancel_button)
self.setLayout(laytout)
self.worker = WorkerThread()
def start(self):
self.worker.is_active = True
self.worker.start()
def stop(self):
self.worker.is_active = False
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
win = Window()
win.show()
sys.exit(app.exec_())
Post a Comment for "Implement A Cancel Button With Qt In Python"