【问题标题】:How to highlight selection in QTreeView programmatically?如何以编程方式突出显示 QTreeView 中的选择?
【发布时间】:2018-07-31 02:17:03
【问题描述】:

当我使用item_selected('Item2') 以编程方式在QTreeView 中选择一个选项时,该选项会按预期传递给处理程序。我还希望该项目具有选择突出显示,但我似乎无法弄清楚。有什么想法吗?

from PyQt5.Qt import Qt
from PyQt5.QtWidgets import QApplication, QTreeWidget, QTreeWidgetItem
import sys


def item_selected(selection):
    try:
        print(selection.text(0))
    except AttributeError:
        print(selection)


app = QApplication(sys.argv)

TreeList = ({
    'Header1': (('Item1', 'Item2', )),
    'Header2': (('Item11', 'Item21', )),
})

tree = QTreeWidget()

for key, value in TreeList.items():
    parent = QTreeWidgetItem(tree, [key])
    for val in value:
        child = QTreeWidgetItem([val])
        child.setFlags(child.flags() | Qt.ItemIsUserCheckable)
        child.setCheckState(0, Qt.Unchecked)
        parent.addChild(child)

tree.itemClicked.connect(item_selected)

tree.show()

# SELECT AND HIGHLIGHT THIS ONE
item_selected('Item2')

sys.exit(app.exec_())

如果上面的代码乱七八糟,请见谅。

【问题讨论】:

  • 你可以使用"selection.setBackground(0, QtGui.QBrush(QtGui.QColor("#FFFF00")))"
  • @NimishBansal 如果我通过使用item_selected('Item2') 进行选择,那将不起作用,因为selection 不再是QTreeViewItem

标签: python python-3.x pyqt pyqt5 qtreeview


【解决方案1】:

你不能使用同一个插槽,它接收一个项目,只打印它,在你的情况下,你必须搜索项目的文本并选择它:

def item_selected(selection):
    print(selection.text(0))

app = QApplication(sys.argv)

TreeList = ({
    'Header1': (('Item1', 'Item2', )),
    'Header2': (('Item11', 'Item21', )),
})

tree = QTreeWidget()

for key, value in TreeList.items():
    parent = QTreeWidgetItem(tree, [key])
    for val in value:
        child = QTreeWidgetItem([val])
        child.setFlags(child.flags() | Qt.ItemIsUserCheckable)
        child.setCheckState(0, Qt.Unchecked)
        parent.addChild(child)

tree.itemClicked.connect(item_selected)

items = tree.findItems("Item2", Qt.MatchFixedString| Qt.MatchRecursive) 
[it.setSelected(True) for it in items]

tree.expandAll()
tree.show()

sys.exit(app.exec_())

【讨论】:

  • 我使用了这个的变体,但这个答案让我走上了正确的道路。答案完全符合预期。
猜你喜欢
  • 2014-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-14
  • 1970-01-01
  • 1970-01-01
  • 2015-12-28
  • 1970-01-01
相关资源
最近更新 更多