공부/Python
7.[Thread]Qt Designer + PyQt5
유저라인
2021. 6. 5. 03:32
728x90
반응형
이렇게 버튼 한개만 추가해주세요
import sys
import threading
import time
from PyQt5.QtWidgets import *
from threading import Thread
import thread_test_ui
class MyWindow(QMainWindow, thread_test_ui.Ui_MainWindow):
def __init__(self):
super().__init__()
self.setupUi(self)
self.pushButton.setCheckable(True)
self.pushButton.clicked.connect(self.pb_start)
def pb_start(self, state):
print(state)
t1 = Thread(target=self.thread_test)
if state:
t1.daemon = True
t1.start()
else:
flag.set()
def thread_test(self):
global flag
flag = threading.Event()
while True:
print("check")
time.sleep(1)
if flag.is_set():
print("stop")
break
if __name__ == "__main__":
app = QApplication(sys.argv)
myApp = MyWindow()
myApp.show()
app.exec_()
1. 버튼을 토글 스위치로 바꿨습니다.
2. 쓰레드를 함수에서 지정해서 썼습니다.
3. 쓰레드 stop을 글로벌 변수와 이벤트를 이용하여 멈춥니다.
4. Daemon 을 추가하여 프로그램이 종료하면 쓰레드도 멈추게 하였습니다.
결과
이렇게 한번 누르면 check 가 계속 나오다가 한번더 누르면 stop 합니다.
728x90
반응형