栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Pyside6 QTextEdit动态显示时间

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Pyside6 QTextEdit动态显示时间

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不兼容的问题,还是什么原因。

参考连接:PyQt学习随笔:QTextEdit和QTextBrowser删除光标所在行内容的方法

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/757548.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号