Python PyQt访问选择更改的内容
如何从选择中获取内容?我有一个表,我想通过它的内容操纵所选项目 该表与selectionModel连接,如下所示:Python PyQt访问选择更改的内容,python,qt,pyqt,Python,Qt,Pyqt,如何从选择中获取内容?我有一个表,我想通过它的内容操纵所选项目 该表与selectionModel连接,如下所示: self.table.selectionModel().selectionChanged.connect(dosomething) 我在函数中得到两个选择,新选择和旧选择。但我不知道如何提取它。别担心,想一想 要获得它,我必须使用: QItemSelection.index()[0].data().toPyObject() 我想这会容易些。如果有人知道一种更像蟒蛇的方式,请回答
self.table.selectionModel().selectionChanged.connect(dosomething)
我在函数中得到两个选择,新选择和旧选择。但我不知道如何提取它。别担心,想一想 要获得它,我必须使用:
QItemSelection.index()[0].data().toPyObject()
我想这会容易些。如果有人知道一种更像蟒蛇的方式,请回答。我意识到这个问题已经很老了,但当我在寻找如何做到这一点时,我通过谷歌找到了它 简言之,我相信你追求的是方法 这里有一个: 导入系统 从PyQt5.QtGui导入QStandardItem、QStandardItemModel 从PyQt5.QtWidgets导入QAbstractItemView、QApplication、QTableView 姓名=[“亚当”、“布赖恩”、“卡罗尔”、“大卫”、“艾米丽”] def选择_已更改(): 选定的\u名称=[表\u视图中idx的名称[idx.row()]。SelectedIndex()] 打印(“选择已更改:”,所选名称) app=QApplication(sys.argv) 表_view=QTableView() model=QStandardItemModel() 表_视图.集合模型(模型) 对于名称中的名称: 项目=QS标准项目(名称) 模型.附录行(项目)
table_view.setSelectionMode(QAbstractItemView.ExtendedSelection)#对于遇到与我相同困惑的任何人,您需要连接到
selectionChanged
信号,而不是currentChanged
。我用currentChanged
尝试此操作,发现selectedIndex()
尚未更新。
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_()