【问题标题】:Change color of line with stylesheet使用样式表更改线条颜色
【发布时间】:2017-03-23 16:56:29
【问题描述】:

我画了一条线,我想设置颜色和线宽。为了使我的应用程序可定制,我希望在样式表中包含此属性。我该怎么做?我尝试子类化QColor,但没有取得多大成功,因为这条线仍然是黑色的。这是我尝试过的:

import sys

from PyQt5.QtWidgets import QWidget, QApplication
from PyQt5.QtGui import QPainter, QColor


class Main(QWidget):
    def paintEvent(self, e):
        painter = QPainter()
        painter.begin(self)

        painter.setPen(LineColor())
        painter.drawLine(0, 0, 100, 100)

        painter.end()


class LineColor(QColor):
    ''' Exposes a class, so that its color can be set using the style sheet '''


qss = '''
LineColor {
    color: red;
}
'''


app = QApplication(sys.argv)
app.setStyleSheet(qss)

main = Main()
main.show()

sys.exit(app.exec_())

【问题讨论】:

    标签: python-3.x qt5 pyqt5 qtstylesheets


    【解决方案1】:

    你正在尝试什么,恕我直言是不可能的。既然你已经继承了QMainWindow,为什么不覆盖setStyleSheet,并解析样式表,并相应地设置颜色?

    class Main(QWidget):
    
        def __init__(...) :
            ...
            ...
            ...
    
            self.myLineColor = QColor( Qt::black )
            ...
            ...
    
        def setStyleSheet( sheet ) :
    
            # Your code to parse the stylesheet
            self.myLineColor.setRgb( ... ) # or setNamedColor or similar.
    
            QMainWindow::setStyleSheet( self, sheet )
    
        def paintEvent(self, e):
            painter = QPainter()
            painter.begin(self)
    
            painter.setPen(self.myLineColor)
            painter.drawLine(0, 0, 100, 100)
    
            painter.end()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-07
      • 1970-01-01
      • 2021-10-31
      • 1970-01-01
      • 2017-10-21
      • 2012-09-10
      • 1970-01-01
      相关资源
      最近更新 更多