如何使用python更改文本框中的特定字母颜色

Posted

技术标签:

【中文标题】如何使用python更改文本框中的特定字母颜色【英文标题】:How to change the particular letter color in text box using python 【发布时间】:2020-02-25 12:18:39 【问题描述】:

我需要使用 python 突出显示文本框中的特定字母。我正在使用下面的代码,但它会更改文本框中的整个文本颜色。请提出任何其他想法。

 if self.dlgAttribute.ui.txtPartDesc3.text()!="":
        partDescValue = self.dlgAttribute.ui.txtPartDesc3.text()
        if not partDescValue in self.englishArray:
            font.setPointSize(11)
            self.dlgAttribute.ui.txtPartDesc3.setFont(font)
            self.dlgAttribute.ui.txtPartDesc3.setStyleSheet(_fromUtf8("color: rgb(255, 162, 0);\n"
            "background-color: rgb(41, 91, 170);\n"
            "font: 750 10pt \"Arial\";"))
        else:
            font.setPointSize(11)
            self.dlgAttribute.ui.txtPartDesc3.setFont(font)
            self.dlgAttribute.ui.txtPartDesc3.setStyleSheet(_fromUtf8("color: rgb(0,0,0);\n"
            "background-color: rgb(255, 255, 255);\n"
            "font: 750 10pt \"Arial\";"))
    else:
        font.setPointSize(11)
        self.dlgAttribute.ui.txtPartDesc3.setFont(font)
        self.dlgAttribute.ui.txtPartDesc3.setStyleSheet(_fromUtf8("color: rgb(0,0,0);\n"
        "background-color: rgb(255, 255, 255);\n"
        "font: 750 10pt \"Arial\";"))

【问题讨论】:

文本框是QLineEdit还是QLabel? 文本框是QLineEdit 【参考方案1】:

一种方法是,使用只读的富文本框,然后复制输入框的纯文本内容并将您想要突出显示的文本替换为 QTextFormat 等。

https://doc.qt.io/qt-5/richtext.html

或者,更简单的方法是将文本转换为 HTML,然后通过 QWebView 动态呈现。

Displaying (rendering) HTML from a string in QT

【讨论】:

这不是一个 Web 应用程序,它是一个独立的桌面应用程序,具有使用 Python 2.7 和 QT Designer 4 开发的简单用户表单。

以上是关于如何使用python更改文本框中的特定字母颜色的主要内容,如果未能解决你的问题,请参考以下文章

如何在ios中更改特定单词的颜色

动态地,在运行时,如何在 WPF 中更改文本框中某些单词的颜色?

如何更改绑定到 Razor 页面上模型的特定文本的字体颜色?

如何在pygame中更改一段文本的颜色

更改 Disqus 评论框中的文本颜色

如何对 QComboBox 中的文本执行字母间距?