QtreeWidget 样式表:更改所选项目样式
Posted
技术标签:
【中文标题】QtreeWidget 样式表:更改所选项目样式【英文标题】:QtTreeWidget stylesheet: change selected item style 【发布时间】:2014-02-28 15:41:55 【问题描述】:我正在尝试更改 QtTreeWidget
中当前选定项目的样式。不幸的是,样式只应用于***项目而不是***的孩子。有没有人遇到过这种情况并有解决办法?
样式表在 QtDesigner 中可以正常工作。我不知道为什么它在我的代码中不起作用。我正在努力将代码提取到一个示例中。
样式表:
QTreeWidget::item:selected border-color:green;
border-style:outset; border-width:2px; color:black;
QTreeWidget::branch:has-children:!has-siblings:closed,
QTreeWidget::branch:closed:has-children:has-siblings
border-image: none;
image: none;
QTreeWidget::branch:open:has-children:!has-siblings,
QTreeWidget::branch:open:has-children:has-siblings
border-image: none;
image: none;
完整示例代码
import sys
from PyQt4 import QtGui, QtCore
class ConditionTree(QtGui.QTreeWidgetItem):
def __init__(self, parent, name):
QtGui.QTreeWidgetItem.__init__(self, parent)
self.tree = parent
self.setText(0, name)
self.button = QtGui.QPushButton(name)
self.button.pressed.connect(self.buttonPress)
def buttonPress(self):
self.setExpanded(not self.isExpanded())
self.tree.setCurrentItem(self)
class mainWindow(QtGui.QMainWindow):
'''
Main window class handeling all gui interactions
'''
def __init__(self, app):
QtGui.QMainWindow.__init__(self)
self.tree = QtGui.QTreeWidget(self)
self.tree.setIndentation(0)
self.tree.setHeaderHidden(True)
self.tree.setStyleSheet('''
QTreeWidget::item:selected border-color:green;
border-style:outset; border-width:2px; color:black;
QTreeWidget::branch:has-children:!has-siblings:closed,
QTreeWidget::branch:closed:has-children:has-siblings
border-image: none;
image: none;
QTreeWidget::branch:open:has-children:!has-siblings,
QTreeWidget::branch:open:has-children:has-siblings
border-image: none;
image: none;
''')
self.topLevel = ConditionTree(self.tree, 'toplevel')
self.tree.setItemWidget(self.topLevel, 0, self.topLevel.button)
for i in range(5):
self.addNewItem(self.topLevel, str(i))
self.tree.resize(self.tree.sizeHint())
def addNewItem(self, toplevel, name):
newItem = QtGui.QTreeWidgetItem()
newItem.setText(0, name)
newItem.setFlags(QtCore.Qt.ItemIsEditable|QtCore.Qt.ItemIsEnabled)
toplevel.addChild(newItem)
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
gui = mainWindow(app)
gui.show()
app.exec_()
app.deleteLater()
sys.exit()
【问题讨论】:
【参考方案1】:子项不可选择。由于您无法选择它们,因此它们不会被设置样式。在addNewItem
方法中修改这一行:
newItem.setFlags(QtCore.Qt.ItemIsEditable|QtCore.Qt.ItemIsEnabled)
到
newItem.setFlags(QtCore.Qt.ItemIsEditable|QtCore.Qt.ItemIsEnabled|QtCore.Qt.ItemIsSelectable)
【讨论】:
所以子项目是可选的,只是默认情况下不是。这解决了问题。谢谢! @Onlyjus:不,QTreeWidgetItem
默认是可选的。但是你在上面做setFlags
。这取代了default value。 您的子项不可选择。以上是关于QtreeWidget 样式表:更改所选项目样式的主要内容,如果未能解决你的问题,请参考以下文章