python - 如何以编程方式突出显示 QTreeView 中的选择?

标签 python python-3.x pyqt pyqt5 qtreeview

当我使用 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_())

抱歉,如果上面的代码一团糟。

最佳答案

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

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_())

enter image description here

关于python - 如何以编程方式突出显示 QTreeView 中的选择?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48890003/

相关文章:

python - 尝试注释哈希变量时,“ABCMeta”对象不可下标

python - PyQt5 - 调整标签大小以填充整个窗口

python - 获取属性错误: im must have seek method while trying to save as GIF

python - 如何使用列表推导式在包含字符串和数字的列表中用转义逗号替换逗号

android - 使用 buildozer kivy 的 800mb apk 文件

python - 如何在不熟悉其来源的 .py 文件的情况下解析我使用的方法的结果?

python - 使用 PyQt4 进行 OpenCV 视频捕获

python - 使用 itemAt 从 QFormLayout 中的 QLineEdit 获取文本

python - 给定另一个索引号列表,将数字插入列表中

python - 将 DICOM 转换为 TIFF