PyQt5定时器实现子窗口定时关闭与重启
PyQt5定时器实现子窗口定时关闭与重启
本文将介绍如何使用PyQt5中的QTimer定时器,在父窗口中控制子窗口的定时关闭与重启。
代码示例pythonfrom PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QPushButtonfrom PyQt5.QtCore import QTimer
class ParentWindow(QMainWindow): def init(self): super().init()
self.child_window = None # 子窗口对象 self.timer = QTimer() # 定时器对象
self.setWindowTitle('Parent Window') self.setGeometry(100, 100, 300, 200)
self.start_button = QPushButton('Start', self) self.start_button.setGeometry(100, 50, 100, 30) self.start_button.clicked.connect(self.start_timer)
self.stop_button = QPushButton('Stop', self) self.stop_button.setGeometry(100, 100, 100, 30) self.stop_button.clicked.connect(self.stop_timer)
self.timer.timeout.connect(self.restart_child_window)
def start_timer(self): if self.child_window is None: self.child_window = ChildWindow() self.child_window.show()
# 设置定时器的超时时间,单位为毫秒 timeout = 5000 # 5秒 self.timer.setInterval(timeout) self.timer.start()
def stop_timer(self): self.timer.stop()
def restart_child_window(self): if self.child_window is not None: self.child_window.close() self.child_window = None
self.start_timer()
class ChildWindow(QWidget): def init(self): super().init()
self.setWindowTitle('Child Window') self.setGeometry(200, 200, 200, 150)
if name == 'main': app = QApplication([]) parent_window = ParentWindow() parent_window.show() app.exec_()
代码解释
-
导入必要的模块: -
QtWidgets: 提供 PyQt5 的界面组件,如窗口、按钮等。 -QtCore: 提供非界面相关的功能,如定时器QTimer。 -
创建父窗口类
ParentWindow: -__init__: 初始化父窗口,创建子窗口对象self.child_window和定时器对象self.timer。 -start_timer: 创建并显示子窗口(如果尚未创建),设置定时器超时时间为5秒,并启动定时器。 -stop_timer: 停止定时器。 -restart_child_window: 关闭子窗口,并将子窗口对象设为None,然后重新调用start_timer方法,实现子窗口的重启。 -
创建子窗口类
ChildWindow: -__init__: 初始化子窗口,设置窗口标题和大小。 -
主程序入口: - 创建 QApplication 对象。 - 创建父窗口对象
parent_window并显示。 - 运行应用程序的事件循环app.exec_()。
运行结果
运行代码后,点击父窗口的 'Start' 按钮,将会打开子窗口。5秒后,子窗口会自动关闭并重新打开。点击 'Stop' 按钮则会停止定时器,子窗口将不再自动关闭和重启。
总结
通过 PyQt5 的 QTimer 定时器,我们可以方便地实现对子窗口的定时关闭和重启。你可以根据实际需求修改定时器的超时时间以及窗口的布局和逻辑,以满足不同的应用场景。
原文地址: https://www.cveoy.top/t/topic/kEh 著作权归作者所有。请勿转载和采集!