Python QLineEdit text color
I am trying to create a demo application to show how to change font colors.
I can do this in QLabel and QTextEdit
I have not found a way to change the foreground text color for QLineEdit.
The only thing I've tried that doesn't throw an error:
color = QColorDialog.getColor(defaultHost.textColor(), pWidget, 'Get Text Color') myPalette.setColor(myPalette.WindowText, QColor(color))
But the text color remains black ...
Is it or is it impossible to do it?
source to share
Below is a snippet of code that took me two days of trial and error. Hope this helps other newbies like me. My comments in the code should help as well.
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:
- how to find the type of widget you are dealing with,
- how to hide a
QColor
fromQColorDialog
a HEX string for use with style; and - how to use
QColorDialog
when the widget does not use the desired type of palette item.
In my case, I am using defaultHost = led_dem.textEdit
where led_dem
is my form and textEdit
is textEdit
in the form.
It is also pWidget
a complete definition of widgets, including form
and instance
.
source to share
this is how i do it without using css
Palette= QtGui.QPalette() Palette.setColor(QtGui.QPalette.Text, QtCore.Qt.red) self.lineEdit.setPalette(Palette)
QLineEdit has initStyleOption method and initStyleOption inherits QStyleOption and then QStyleOption has QPalette method. You can now follow the recommendations of the QPalette methods.
you can visit this link for reference http://pyqt.sourceforge.net/Docs/PyQt4/qlineedit.html
source to share