Skip to main content

PySide2 QTimer


QTimer

PySide2.QtCore.QTimer 클래스를 사용하면 반복적인 작업이나 일정 시간 후 실행되는 작업을 처리할 수 있습니다.

Single shot timer

singleShot()은 일정 시간이 지난 후, 작업이 시작되도록 할 수 있게 해주는 함수입니다. static 함수이기 때문에 인스턴스를 만들지 않고 사용할 수 있습니다.

아래 코드는 푸시 버튼과 텍스트 브라우저 위젯이 있을 때, 버튼을 누르면 1 초 후에 텍스트를 띄우는 코드입니다.

import sys

from PySide2.QtWidgets import QMainWindow, QApplication
from PySide2.QtCore import QTimer, SLOT

from ui_mainwindow import Ui_MainWindow


class MainWindow(QMainWindow, Ui_MainWindow):
def __init__(self):
super().__init__()

self.setupUi(self)
self.pushButton.setText("버튼 1")

self.pushButton.clicked.connect(self.pushButtonClicked)

def pushButtonClicked(self):
"""
1 초 타임아웃과 appendTextBrowser 연결
QTimer.singleShot(1000, self, SLOT("appendTextBrowser()"))
QTimer.singleShot(
1000, Qt.PreciseTimer, self, SLOT("appendTextBrowser()")
)
"""
QTimer.singleShot(1000, self.appendTextBrowser)

def appendTextBrowser(self):
self.textBrowser.append("1 초 후")


if __name__ == "__main__":
app = QApplication(sys.argv)
mainWindow = MainWindow()
mainWindow.show()
sys.exit(app.exec_())
info

Linux와 Windows에서 타이머는 차이가 있습니다.
Qt.TimerType: https://doc.qt.io/qtforpython/PySide2/QtCore/Qt.html

Repetitive timer

반복 실행은 인스턴스 함수를 사용하기 때문에 QTimer의 인스턴스를 생성해야합니다.

아래 코드는 푸시 버튼과 텍스트 브라우저 위젯이 있을 때, 버튼을 누르면 1 초 간격으로 3 회 텍스트를 띄우는 코드입니다.

import sys

from PySide2.QtWidgets import QMainWindow, QApplication
from PySide2.QtCore import QTimer

from ui_mainwindow import Ui_MainWindow


class MainWindow(QMainWindow, Ui_MainWindow):
def __init__(self):
super().__init__()

self.setupUi(self)
self.pushButton.setText("버튼 1")

self.pushButton.clicked.connect(self.pushButtonClicked)

self.isPushButtonClicked = False

self.pushButtonTimer = QTimer(self)
self.pushButtonTimer.setInterval(1000)
self.pushButtonTimer.timeout.connect(self.appendTextBrowser)

self.count = 0

def pushButtonClicked(self):
if not self.isPushButtonClicked:
self.isPushButtonClicked = True
self.pushButton.setEnabled(False)

"""
반복 시작
"""
self.pushButtonTimer.start()

def appendTextBrowser(self):
self.count += 1
self.textBrowser.append(str(self.count) + " 초 후")

if self.count == 3:
"""
반복 종료
"""
self.pushButtonTimer.stop()
self.isPushButtonClicked = False
self.pushButton.setEnabled(True)
self.count = 0


if __name__ == "__main__":
app = QApplication(sys.argv)
mainWindow = MainWindow()
mainWindow.show()
sys.exit(app.exec_())

Reference