如果我使用setStyleSheet
方法来更改特定小部件的样式,则放置在其中的其他小部件会更改其样式,但我不想要它!我可以给你举两个例子:
当我更改框架的边框/背景色时(请参见放置在框架内的小部件):
import PyQt5.QtGui as qtg
import PyQt5.QtCore as qtc
import PyQt5.QtWidgets as qtw
import sys
class MainWindow(qtw.QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.resize(520,300)
self.setWindowTitle("Treeview Example")
self.layout = qtw.QVBoxLayout()
self.frame1=qtw.QFrame()
self.frame1layout=qtw.QVBoxLayout()
self.frame1layout.setContentsMargins(5, 5, 5, 5)
self.frame1.setLayout(self.frame1layout)
self.frame1.setStyleSheet("border: 1px solid; border-color:red; background-color:white") # I change the style for the main frame
self.layout.addWidget(self.frame1)
self.frame2=qtw.QFrame()
self.frame2layout=qtw.QVBoxLayout()
self.frame2layout.setContentsMargins(10, 10, 10, 10)
self.frame2.setLayout(self.frame2layout)
self.frame1layout.addWidget(self.frame2)
self.ProgressBar=qtw.QProgressBar()
self.frame2layout.addWidget(self.ProgressBar)
self.setLayout(self.layout)
if __name__ == '__main__':
app = qtw.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
或者当我更改treeview小部件的边框颜色时(滚动的treeview小部件变为白色):
import PyQt5.QtGui as qtg
import PyQt5.QtCore as qtc
import PyQt5.QtWidgets as qtw
import sys
class MainWindow(qtw.QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.resize(520,300)
self.setWindowTitle("Treeview Example")
self.layout = qtw.QVBoxLayout()
self.treeview = qtw.QTreeView(self)
self.treeview.setStyleSheet("border: 1px solid; border-color:red") # it destroy the style of the objects inside the treeview widget!
model = qtg.QStandardItemModel()
rootNode = model.invisibleRootItem()
section1 = qtg.QStandardItem("A")
section1.appendRow([qtg.QStandardItem("A1")])
childnode = qtg.QStandardItem("A2")
section1.appendRow([childnode])
section2 = qtg.QStandardItem("B")
section2.appendRow([qtg.QStandardItem("B1")])
section2.appendRow([qtg.QStandardItem("B2")])
rootNode.appendRow([section1])
rootNode.appendRow([section2])
self.treeview.setHeaderHidden(True)
self.treeview.setModel(model)
self.layout.addWidget(self.treeview)
self.setLayout(self.layout)
if __name__ == '__main__':
app = qtw.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
我的问题是,如何在不修改其他小部件样式的情况下更改特定小部件的样式
########### 更新:
在我的第一个示例中,如果我不使用指令self.treeview.setStyleSheet("border: 1px solid; border-color:red")
,我意识到进度条小部件不会像以前那样展开。请参见此屏幕截图:
问题是什么
我强烈建议您更仔细地阅读style sheet syntax和reference文档,因为这里对所有内容都有明确的说明和解释:
根据定义,样式表是级联的
小部件上的样式表集在其子部件上传播,这些子部件继承父部件的样式
如果像这样设置常规属性:
结果是,所有的子项都将具有该边界:您只给出了声明,但没有选择器,因此通用选择器被用作隐式选择器
这不仅仅是Qt,这是典型的CSS(QS从中获取其主要概念),它的工作原理与任何其他小部件样式属性完全相同:在小部件上设置字体或调色板,将它们传播到其所有子部件。
不同之处在于,对于样式表(与标准CSS完全相同),您可以使用selectors
如果只想设置树小部件的样式,请使用该类选择器:
相关问题 更多 >
编程相关推荐