Skip to main content
 首页 » 编程设计

python之如何设置Qframe边框的颜色

2024年12月31日9开发

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

没有任何样式表。

带边框样式表的输出

使用背景色样式表

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

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

请您参考如下方法:

您可以使用 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_())