PyQt acess selectionChanged Content

问题描述 投票:0回答:2

如何从选择中获取内容?我有一张桌子,我想通过其内容操纵所选项目。

该表与selectionModel连接,如下所示:

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

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

python qt pyqt
2个回答
0
投票

没关系,弄清楚。

要得到它我必须使用:

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

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


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_()
© www.soinside.com 2019 - 2024. All rights reserved.