如何从选择中获取内容?我有一张桌子,我想通过其内容操纵选定的项目。访问选项更改内容
该表是连接与这样的selectionModel设置:
self.table.selectionModel().selectionChanged.connect(dosomething)
我的功能,新的选择和老拿到两QItemSelection。但我不知道如何提取它。
如何从选择中获取内容?我有一张桌子,我想通过其内容操纵选定的项目。访问选项更改内容
该表是连接与这样的selectionModel设置:
self.table.selectionModel().selectionChanged.connect(dosomething)
我的功能,新的选择和老拿到两QItemSelection。但我不知道如何提取它。
没关系,搞明白了。
为了得到它,我不得不使用:
QItemSelection.index()[0].data().toPyObject()
我认为它会更容易些。如果有人知道更pythonic的方式,请回复。
我意识到这个问题是相当古老的,但当我正在寻找如何做到这一点时,我通过Google找到了它。
总之,我相信你所追求的是方法selectedIndexes()
。
这里有一个最小的工作示例:
import sys
from PyQt5.QtGui import QStandardItem, QStandardItemModel
from PyQt5.QtWidgets import QAbstractItemView, QApplication, QTableView
names = ["Adam", "Brian", "Carol", "David", "Emily"]
def selection_changed():
selected_names = [names[idx.row()] for idx in table_view.selectedIndexes()]
print("Selection changed:", selected_names)
app = QApplication(sys.argv)
table_view = QTableView()
model = QStandardItemModel()
table_view.setModel(model)
for name in names:
item = QStandardItem(name)
model.appendRow(item)
table_view.setSelectionMode(QAbstractItemView.ExtendedSelection) # <- optional
selection_model = table_view.selectionModel()
selection_model.selectionChanged.connect(selection_changed)
table_view.show()
app.exec_()