如何编程点击 QTreeWidgetItem
有一个函数会在用户点击 QTreeWidgetItem 时被触发。我想知道有没有办法通过代码来“点击”一个项目。我试过
.setCurrentIndex(index)
.setCurrentItem(item)
但是这些方法虽然能让这个项目变成“激活”状态,却并不会触发 onClick 函数。
2 个回答
3
这里有一些代码片段,可以模拟在QTreeWidget中的某个项目上点击鼠标。我希望这对你有帮助。
# get the QTreeWidget object
treeWidget = self.form.treeWidget
# obtain the 0th child item of the 0th top level item
child = treeWidget.topLevelItem(0).child(0)
# obtain the rectangular coordinates of the child item
rect = treeWidget.visualItemRect(child)
# simulate the mouse click within the rectangular coordinates
QTest.mouseClick(treeWidget.viewport(), Qt.LeftButton, Qt.NoModifier,rect.center())
2
- 把信号
treeWidget.currentItemChanged
连接到 onClick 这个函数上 - 获取当前选中的项目,并把它存到一个变量里
- 使用
setCurrentItem(item)
方法来改变当前选中的项目
treeWidget.currentItemChanged.connect(onClick)
previousItem = treeWidget.currentItem()
treeWidget.setCurrentItem(item)
def onClick(current, previous):
print current.text(0) if current is not None else None # put the whatever index your item has
print previous.text(0) if previous is not None else None