I am trying to create a demonstration app to show how to change font colors.
I can do it in QLabel and QTextEdit
I have found no way to change the foreground
You can do it by setting the object's style sheet:
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;
}
""")
Below is a code snippet that took me two days of trial and error to figure out. I hope it helps other newbies like myself. My comments in the code should help, too.
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)
This snippet shows:
QColor
from a QColorDialog
into a string HEX format for use with a stylesheet; andQColorDialog
when the widget doesn't use a palette element of the type you need. In my case I am using defaultHost = led_dem.textEdit
where led_dem
is my form and textEdit
is a textEdit
on the form.
Also, pWidget
is the complete widget definition including form
and instance
.
I solved for font text and background
self.my_line_edit.setStyleSheet(
"""QLineEdit { background-color: green; color: white }""")
this is how I do it not using css
Palette= QtGui.QPalette()
Palette.setColor(QtGui.QPalette.Text, QtCore.Qt.red)
self.lineEdit.setPalette(Palette)
QLineEdit has a method initStyleOption and initStyleOption inherits QStyleOption, and then QStyleOption has a Method QPalette. Now you can take advatage of using QPalette methods.
you can visit this link for reference http://pyqt.sourceforge.net/Docs/PyQt4/qlineedit.html