Reputation: 6159
I am trying to change the style of the current selected item in a QtTreeWidget
. Unfortunately, the styling is only applied to the toplevel items and not the toplevel's children. Has anyone encountered this before and have a solution?
The stylesheet works correctly in QtDesigner. I don't know why it doesn't work in my code. I am working on pulling out the code into an example.
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()
Upvotes: 1
Views: 3184
Reputation: 36725
Child items are not selectable. Since you cannot select them, they won't be styled. Modify this line in addNewItem
method:
newItem.setFlags(QtCore.Qt.ItemIsEditable|QtCore.Qt.ItemIsEnabled)
to
newItem.setFlags(QtCore.Qt.ItemIsEditable|QtCore.Qt.ItemIsEnabled|QtCore.Qt.ItemIsSelectable)
Upvotes: 2