PyQt访问selectionChanged内容

2024-09-29 17:11:38 发布

您现在位置:Python中文网/ 问答频道 /正文

如何从选择中获取内容?我有一个表,我想通过它的内容来操作所选的项。在

该表使用如下selectionModel连接:

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

函数中有两个QItemSelection,新的和旧的。但我不知道如何提取。在


Tags: 函数self内容connecttabledosomethingselectionmodelselectionchanged
2条回答

别担心,想办法。在

为了得到它,我不得不使用:

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

我以为会更容易些。如果有人知道更Python的方式,请回答。在

我意识到这个问题很古老,但我是在寻找如何做到这一点时通过谷歌找到的。在

简而言之,我相信你所追求的是方法^{}。在

下面是一个最小的工作示例:

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_()

相关问题 更多 >

    热门问题