PyQt acess selectionChanged Content

时间:2014-04-27 14:37:07

标签: python qt pyqt

如何从选择中获取内容?我有一张桌子,我希望按照其内容操纵所选项目。

该表与这样的selectionModel连接:

self.table.selectionModel().selectionChanged.connect(dosomething)

我在函数中得到两个QItemSelection,新的选择和旧的。但我不知道如何提取它。

2 个答案:

答案 0 :(得分:0)

没关系,弄清楚。

要得到它,我必须使用:

QItemSelection.index()[0].data().toPyObject()

我觉得这会更容易。如果有人知道更多的pythonic方式,请回复。

答案 1 :(得分:0)

我意识到这个问题很老了,但是当我在寻找如何做到这一点时,我通过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_()