【问题标题】:how to set color of frame of Qframe?如何设置Qframe框架的颜色?
【发布时间】:2018-06-27 07:33:13
【问题描述】:

我想在 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

没有任何样式表。

带边框样式表的输出

背景色样式表

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

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

【问题讨论】:

  • 我有个大问题,你想要什么输出?
  • 第一个输出为蓝色,没有“厚度”

标签: python pyside2 qframe


【解决方案1】:

您可以使用QPalette,而不是使用Qt 样式表:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-22
    • 2014-03-21
    • 2019-06-25
    • 1970-01-01
    • 1970-01-01
    • 2014-03-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多