如何将水平渐变分配给 QLineEdit 背景

How to assign the horizontal gradient to QLineEdit background

该代码创建了一个 QLineEdit,其背景从上到下渐变 运行。如何使渐变从一侧到另一侧(本质上是将用作背景的垂直渐变变为水平渐变)?

    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()

让渐变从左上角到右上角,您走在了正确的轨道上。问题是 QLineEdit 还没有最终的形状,所以它的 rect() 太大了。如果您在 line.show() 之后设置渐变,它会起作用。请参阅下面的示例:

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_())