Pyside6 QTextEdit动态显示时间
最近在做一个项目,需要定时更新时间,网上搜了很多资料,然后自己摸索,终于实现了,下面做下记录。
项目使用Python3.9 + PySide6,APScheduler作为任务调度。点清空输出按钮后,每隔秒更新一次时间,也就是调用一次test()函数实现更新显示。
具体流程如下:
获取当前光标位置 -> 选中光标所在的行 -> 移除选中的内容 -> 光标移动到行起始位置 -> 设定光标位置 -> 插入文本内容。
主要代码如下:
# -*- coding: utf-8 -*-
from PySide6.QtGui import QTextCursor
from PySide6.QtWidgets import QMainWindow
from PySide6.QtCore import Slot
from PySide6.QtGui import QTextCursor
from ui_mainwindow import Ui_MainWindow # 图形界面文件
from apscheduler.schedulers.qt import QtScheduler # Qt任务调度
class TestClass(QMainWindow):
def __init__():
super(TestClass, self).__init__()
self.window = Ui_MainWindow()
self.window.setupUi(self)
self.window.timingClearButton.clicked.connect(self.test_button) # 连接信号槽
# 其余代码省略
def test(self):
now = datetime.strftime(datetime.now(), "%Y-%m-%d %H:%M:%S")
# self.timing_print_text('开始.....')
cursor = self.window.timingOutputText.textCursor() # 获取当前光标
cursor.select(QTextCursor.LineUnderCursor) # 选中光标行
cursor.removeSelectedText()
cursor.movePosition(QTextCursor.StartOfLine) # 光标移动到行首
self.window.timingOutputText.setTextCursor(cursor) # 设定光标位置
self.window.timingOutputText.insertPlainText(now + '-----')
@Slot()
def test_button(self):
"""
Timing模式-清空输出
"""
self.timing_print_text('开始.....\n')
scheduler = QtScheduler(timezone="Asia/Shanghai") # 创建任务调度
# 存储数据,每隔1s执行一次
scheduler.add_job(
self.test,
"interval",
seconds=1,
)
scheduler.start() # 启动任务调度
代码中timingOutputText 是输出区域的对象。
界面如下图:
代码实现了点击清空输出按钮,每隔1秒更新显示的时间。
需要注意的是,输出文本内容不能使用 setText(), setPlainText()等带的函数,只能使用insertPlainText(),append()否则会提示如下的错误:
QObject: Cannot create children for a parent that is in a different thread.
(Parent is QTextDocument(0x17d6af9bee0), parent's thread is QThread(0x17d699706c0), current thread is QThread(0x17d6afffb00)
弹出python.exe- 应用程序错误,然后软件就退出了。
如果单独使用,不使用apscheduler的话,连续点击按钮并不会出现这个错误,所以不知道是apscheduler框架与PySide6不兼容的问题,还是什么原因。