PyQt 访问 selectionChanged 内容

1 投票
2 回答
3258 浏览
提问于 2025-04-18 04:28

我该如何获取选中内容呢?我有一个表格,想根据选中的内容来操作它。

这个表格是通过一个叫做selectionModel的东西连接起来的,像这样:

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

在这个函数里,我得到了两个QItemSelection,一个是新的选中项,另一个是旧的选中项。但我不知道怎么提取这些内容。

2 个回答

3

我知道这个问题已经有点时间了,但我在谷歌上搜索相关内容时找到了它。

简单来说,我认为你想要的就是这个方法 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_()
2

没事,自己想办法解决吧。

为了搞定这个,我用了:

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

我原以为会简单一些。如果有人知道更符合Python风格的方法,请回复我。

撰写回答