- 1 year ago
How to disable focus border and background it QTreeWidget with fusion style?
To disable the focus border and background in a QTreeWidget
using the Fusion style in Qt, you can customize the item delegate and override the paint()
function to exclude drawing the focus border and background. Here's an example:
pythonfrom PyQt5.QtWidgets import QApplication, QTreeWidget, QStyledItemDelegate, QStyleOptionViewItem
from PyQt5.QtCore import Qt, QRect
class CustomItemDelegate(QStyledItemDelegate):
def paint(self, painter, option, index):
# Exclude drawing focus border and background
if option.state & QStyleOptionViewItem.HasFocus:
option.state &= ~QStyleOptionViewItem.HasFocus
option.state &= ~QStyleOptionViewItem.Selected
# Call the base class implementation to paint the item
super().paint(painter, option, index)
if __name__ == '__main__':
app = QApplication([])
# Apply Fusion style
app.setStyle('Fusion')
tree_widget = QTreeWidget()
tree_widget.setItemDelegate(CustomItemDelegate()) # Set the custom item delegate
# Add items to the tree widget
item1 = tree_widget.invisibleRootItem().addChild(["Item 1"])
item2 = tree_widget.invisibleRootItem().addChild(["Item 2"])
tree_widget.show()
app.exec_()
In this example, we create a custom item delegate (CustomItemDelegate
) by subclassing QStyledItemDelegate
. In the paint()
function of the custom delegate, we modify the option
parameter to remove the focus border and background by clearing the HasFocus
and Selected
states.
We then set the custom item delegate on the QTreeWidget
using the setItemDelegate()
method.
By running this code, the QTreeWidget
will be displayed with the Fusion style, and the focus border and background will be disabled for all items.
Please note that this example is written in Python using PyQt5. The same concept can be applied in C++ using the Qt framework.