質問

How do I get the content from a selection? I have a table and I want to manipulate the selected item by its content.

The table is connect with a selectionModel like this:

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

I get two QItemSelection in the function, the new selection and the old. But I don't know how to extract it.

役に立ちましたか?

解決 2

Nevermind, figure it out.

To get it I had to use:

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

I thought it would be easier. If anyone know a more pythonic way, please reply.

他のヒント

I realise this question is quite old, but I found it via Google when I was looking for how to do this.

In short what I believe you're after is the method selectedIndexes().

Here's a minimal working example:

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_()
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top