更改 QString 或 QLineEdit 的颜色和字体

Change the Color and Font of QString or QLineEdit

如何更改QLineEdit的颜色和字体?

这是我的代码:

self.lineEdit = QtGui.QLineEdit(widget)
self.lineEdit.setText("enter keywords here") #I want this to be in italics and in brown color

DocumentationsetText 行说里面的文本是 QString 我怎样才能改变它的字体和颜色?

您可以通过以下方式更改颜色:

self.lineEdit.setStyleSheet("color: rgb(x,x,x)")

字体大小:

self.lineEdit.setStyleSheet("fontName='Times-Italic'")

颜色使用QPallete,然后使用{your palette}.setColor(QtGui.QPalette.Text, {your QColor}),字体使用QFont

我的解决方案:

from PyQt4 import QtGui

from PyQt4 import QtCore


if __name__ == '__main__':
    import sys
    app = QtGui.QApplication(sys.argv)
    w = QtGui.QLineEdit()
    palette = QtGui.QPalette()
    palette.setColor(QtGui.QPalette.Text, QtCore.Qt.red)
    w.setPalette(palette)
    font = QtGui.QFont("Times", 15, QtGui.QFont.Bold)
    w.setFont(font)
    w.show()
    sys.exit(app.exec_())

在 pyqt5 中,您也可以通过这种方式使用 StyleSheet:

qrc = """
 /* Main LineEdit Setting */
 QLineEdit{
    background-color: #18181d;
    color: red;
    border-radius: 20%;
    height: 2.6em;

    font-weight: bold;
    font-family: 'Times New Roman';
 }

 /* when in hover */
 QLineEdit:hover{
    background-color: #25252d;
 }

 /* when has focus */
 QLineEdit:focus{
    border: 2px solid #13c386; 
    background-color: #25252d;
 }
"""
self.lineEdit.setStyleSheet(qrc)