【问题标题】:How to assign the horizontal gradient to QLineEdit background如何将水平渐变分配给 QLineEdit 背景
【发布时间】:2016-05-02 01:08:01
【问题描述】:

代码创建了一个 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()

【问题讨论】:

    标签: qt pyqt qtgui qlineedit


    【解决方案1】:

    让渐变从左上角到右上角是正确的。问题是 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_())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多