2

我想在 pyside2 中设置 QFrame 提供的框架颜色。

以下文档提供了完整的详细信息,如何创建具有不同样式的框架,如框、面板、Hline 等...

https://doc-snapshots.qt.io/qtforpython/PySide2/QtWidgets/QFrame.html#detailed-description

我的问题是如何设置该框架的颜色。我尝试使用“背景颜色”和“边框”样式表设置颜色,但没有得到我想要的输出。

下面是我的代码。

class HLine(QFrame):
    def __init__(self, parent=None, color="black"):
        super(HLine, self).__init__(parent)
        self.setFrameShape(QFrame.HLine)
        self.setFrameShadow(QFrame.Plain)
        self.setLineWidth(0)
        self.setMidLineWidth(3)
        self.setContentsMargins(0, 0, 0, 0)
        self.setStyleSheet("border:1px solid %s" % color)

    def setColor(self, color):
        self.setStyleSheet("background-color: %s" % color)
        pass

没有任何样式表。

在此处输入图像描述

带边框样式表的输出

在此处输入图像描述

带背景色样式表

在此处输入图像描述

两者都是样式表,提供不需要的输出。

如何在不改变框架外观的情况下设置颜色?

4

1 回答 1

1

代替使用 Qt 样式表,您可以使用QPalette

import sys
from PySide2.QtCore import Qt
from PySide2.QtGui import QColor, QPalette
from PySide2.QtWidgets import QApplication, QFrame, QWidget, QVBoxLayout


class HLine(QFrame):
    def __init__(self, parent=None, color=QColor("black")):
        super(HLine, self).__init__(parent)
        self.setFrameShape(QFrame.HLine)
        self.setFrameShadow(QFrame.Plain)
        self.setLineWidth(0)
        self.setMidLineWidth(3)
        self.setContentsMargins(0, 0, 0, 0)
        self.setColor(color)

    def setColor(self, color):
        pal = self.palette()
        pal.setColor(QPalette.WindowText, color)
        self.setPalette(pal)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = QWidget()
    w.resize(400, 400)
    lay = QVBoxLayout(w)
    lay.addWidget(HLine())

    for color in [QColor("red"), QColor(0, 255, 0), QColor(Qt.blue)]:
        h = HLine()
        h.setColor(color)
        lay.addWidget(h)

    w.show()
    sys.exit(app.exec_())

在此处输入图像描述

于 2018-06-27T07:59:19.210 回答