我画了一条线,我想设置颜色和线宽。为了使我的应用程序可自定义,我希望在样式表中具有此属性。我该怎么做?我试图对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_())
您正在尝试的,恕我直言是不可能的。既然你已经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()