繁体   English   中英

python QLineEdit 文本颜色

[英]python QLineEdit Text Color

我正在尝试创建一个演示应用程序来展示如何更改字体颜色。

我可以在 QLabel 和 QTextEdit 中做到

我发现无法更改 QLineEdit 的前景色文本颜色。

我尝试过的唯一不会抛出错误的是:

color = QColorDialog.getColor(defaultHost.textColor(), pWidget, 'Get Text Color')
myPalette.setColor(myPalette.WindowText, QColor(color))

但是,文本颜色仍然是黑色...

是否可以这样做?

您可以通过设置对象的样式表来实现

self.my_line_edit = QtGui.QLineEdit()

self.my_line_edit.setStyleSheet("color: red;")

# or

self.my_line_edit.setStyleSheet("color: rgb(255, 0, 0);")

# or

self.my_line_edit.setStyleSheet("""
    QLabel {
        color: red;
    }
    """)

我解决了字体文本和背景

 self.my_line_edit.setStyleSheet(
                """QLineEdit { background-color: green; color: white }""")

下面是一段代码片段,我花了两天时间反复试验才弄明白。 我希望它可以帮助像我这样的其他新手。 我在代码中的注释也应该有所帮助。

def set_palette(pWidget, pItem):
    # Get the pallet
    myPalette = pWidget.palette()
    defaultHost = led_dem.textEdit

    if isinstance(pWidget, QPushButton):
        # NOTE: Using stylesheets will temporarily change the color dialog popups push buttons
        print "Instance Is: %s " %(pWidget.objectName())
        # Existing colors.
        bgColor = pWidget.palette().color(QPalette.Background)
        fgColor = pWidget.palette().color(QPalette.Foreground)
        # Convert the QColors to a string hex for use in the Stylesheet.
        bg = bgColor.name()
        fg = fgColor.name()

        if pItem == 'Text':
            # Use the color dialog with a dummy widget to obtain a new QColor for the parameter we are changing.
            color = QColorDialog.getColor(defaultHost.textColor(), pWidget, 'Get Text Color')
            # Convert it to a string HEX
            fg = color.name()
            # Update all parameters of interest
            pWidget.setStyleSheet('background-color: ' + bg + ';color: ' + fg)

        if pItem == 'Background':
            color = QColorDialog.getColor(defaultHost.textColor(), pWidget, 'Get Background Color')
            myPalette.setColor(myPalette.Base, QColor(color))
            bg = color.name()
            pWidget.setStyleSheet('background-color: ' + bg + ';color: ' + fg)

这个片段显示:

  • 如何找到您正在处理的小部件类型;
  • 如何将QColorQColorDialog转换为字符串 HEX 格式以与样式表一起使用;
  • 当小部件不使用您需要的类型的调色板元素时如何使用QColorDialog

就我而言,我使用的是defaultHost = led_dem.textEdit其中led_dem是我的表单,而textEdittextEdit上的textEdit

此外, pWidget是完整的小部件定义,包括forminstance

这就是我不使用 css 的方式

Palette= QtGui.QPalette()
Palette.setColor(QtGui.QPalette.Text, QtCore.Qt.red)
self.lineEdit.setPalette(Palette)

QLineEdit 有一个方法initStyleOption ,initStyleOption 继承了QStyleOption,然后QStyleOption 有一个Method QPalette。 现在您可以利用 QPalette 方法。

您可以访问此链接以供参考http://pyqt.sourceforge.net/Docs/PyQt4/qlineedit.html

对我来说,这是第一次尝试:
self.LBLDefteraStatusState.setStyleSheet('color: green;')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM