我有一个二维的QTreeWidget,如何单击该项目?我使用PyQt5。我有这部分代码,但是它仅获取所选行的第一项(或通过更改baseNode.text(#)来获取其他任何项)
...
self.treeWidget.itemSelectionChanged.connect(lambda: loadAllMessages())
def loadAllMessages():
getSelected = self.treeWidget.selectedItems()
if getSelected:
baseNode = getSelected[0]
getChildNode = baseNode.text(0)
print(getChildNode)
...
答案 0 :(得分:1)
您只需要使用QTreeWidgetItem
发送的itemClicked
信号和单击的列:
示例:
from PyQt5 import QtCore, QtGui, QtWidgets
class Widget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(Widget, self).__init__(parent)
lay = QtWidgets.QVBoxLayout(self)
tree = QtWidgets.QTreeWidget()
tree.setColumnCount(2)
lay.addWidget(tree)
for i in range(4):
parent_it = QtWidgets.QTreeWidgetItem(["{}-{}".format(i, l) for l in range(2)])
tree.addTopLevelItem(parent_it)
for j in range(5):
it = QtWidgets.QTreeWidgetItem(["{}-{}-{}".format(i, j, l) for l in range(2)])
parent_it.addChild(it)
tree.expandAll()
tree.itemClicked.connect(self.onItemClicked)
@QtCore.pyqtSlot(QtWidgets.QTreeWidgetItem, int)
def onItemClicked(self, it, col):
print(it, col, it.text(col))
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec_())