我正在尝试更改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()
答案 0 :(得分:2)
子项目不可选。由于无法选择它们,因此不会对它们进行样式设置。在addNewItem
方法中修改此行:
newItem.setFlags(QtCore.Qt.ItemIsEditable|QtCore.Qt.ItemIsEnabled)
到
newItem.setFlags(QtCore.Qt.ItemIsEditable|QtCore.Qt.ItemIsEnabled|QtCore.Qt.ItemIsSelectable)