The code creates a QLineEdit with the background gradient running from top to bottom. How to make the gradient to go from side to side (essentially turn the Vertical to Horizontal gradient used as background)?
line = QtGui.QLineEdit()
gradient = QtGui.QLinearGradient( QtCore.QRectF(line.rect()).topRight(), QtCore.QRectF(line.rect()).bottomRight() ) # top bottm
gradient = QtGui.QLinearGradient( QtCore.QRectF(line.rect()).topLeft(), QtCore.QRectF(line.rect()).topRight() ) # top bottm
gradient.setColorAt(0.0, QtGui.QColor("blue"))
gradient.setColorAt(1.0, QtGui.QColor("red"))
brush = QtGui.QBrush(gradient)
palette = line.palette()
palette.setBrush(QtGui.QPalette.Base, brush)
line.setPalette(palette)
line.show()
You were on the right track with letting the gradient go from the top-left to the top-right corner. The problem was that the QLineEdit did not yet have the final shape so its rect()
was too large. If you set the gradient after line.show()
it works. See my example below:
import sys
from PyQt4 import QtGui, QtCore
app = QtGui.QApplication(sys.argv)
line = QtGui.QLineEdit()
rect = QtCore.QRectF(line.rect())
print rect # 640 by 480 pixels
line.show()
rect = QtCore.QRectF(line.rect())
print rect # 200 by 21 pixels
horGradient = QtGui.QLinearGradient(rect.topLeft(), rect.topRight())
verGradient = QtGui.QLinearGradient(rect.topLeft(), rect.bottomLeft())
gradient = horGradient
gradient.setColorAt(0.0, QtGui.QColor("blue"))
gradient.setColorAt(1.0, QtGui.QColor("red"))
brush = QtGui.QBrush(gradient)
palette = line.palette()
palette.setBrush(QtGui.QPalette.Base, brush)
line.setPalette(palette)
sys.exit(app.exec_())