pyqt5实现定时的显示:

1.使用:
import time
time.sleep(1) # 暂停一秒
会导致程序卡顿 !!!

2.可以使用 PyQt5 的 QTimer 类来实现定时器功能,以便实现实时的显示。这样可以避免阻塞主线程,让程序保持响应

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QVBoxLayout, QWidget, QTextEdit
from PyQt5.QtCore import QTimer
from io import StringIO

class OutputLogger(object):
    def __init__(self, text_edit):
        self.text_edit = text_edit
        self.buffer = StringIO()

    def write(self, message):
        self.buffer.write(message)
        cursor = self.text_edit.textCursor()
        cursor.movePosition(cursor.End)
        cursor.insertText(message)
        self.text_edit.setTextCursor(cursor)
        self.text_edit.ensureCursorVisible()

    def flush(self):
        pass

class MyWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle('Redirect Output to QTextEdit')

        # 创建一个文本框
        self.text_edit = QTextEdit()
        self.text_edit.setReadOnly(True)

        # 创建一个按钮来触发输出
        self.button = QPushButton('Click me', self)
        self.button.clicked.connect(self.on_button_clicked)

        # 设置布局
        layout = QVBoxLayout()
        layout.addWidget(self.text_edit)
        layout.addWidget(self.button)

        # 创建主窗口的中心部件
        central_widget = QWidget()
        central_widget.setLayout(layout)
        self.setCentralWidget(central_widget)

        # 创建定时器,每秒触发一次,
        # 它创建了一个新的QTimer对象,并将它赋值给了self.timer变量。这个QTimer对象用于触发定时事件。
        self.timer = QTimer(self)
        # ,将self.print_next_number方法与定时器的timeout信号关联起来。每当定时器超时时(即达到设定的时间间隔),它会发出timeout信号,这个信号会触发与之连接的槽函数,即self.print_next_number方法。
        self.timer.timeout.connect(self.print_next_number)

    def on_button_clicked(self):
        # 将输出重定向到文本框
        sys.stdout = OutputLogger(self.text_edit)
        # 启动定时器
        self.counter = 0
        # self.timer.start(1000)启动了定时器,并设定了定时器的触发间隔为1000毫秒,即1秒。这样,定时器就会在1秒钟后开始触发timeout信号,并调用与之关联的self.print_next_number方法。
        self.timer.start(1000)  # 每秒触发一次

    def print_next_number(self):
        # 输出数字和文本
        self.counter += 1
        print(self.counter)
        print('Hello, world!')
        print('This is a test.')
        # 输出完毕后停止定时器
        if self.counter >= 1000:
            self.timer.stop()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MyWindow()
    window.show()
    sys.exit(app.exec_())

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值