pyqt5中,indexes = table.selectionModel().selectedRows(),通过index获取单元格值
时间: 2024-02-03 14:13:04 浏览: 30
可以使用以下代码获取选中单元格的值:
```python
indexes = table.selectionModel().selectedIndexes()
for index in indexes:
row = index.row()
column = index.column()
value = table.item(row, column).text()
print(value)
```
其中,`indexes`获取所有选中单元格的索引,遍历每个索引,通过`row()`和`column()`方法获取行和列的索引,再通过`item()`方法获取单元格对象,并使用`text()`方法获取单元格的值。
相关问题
editor = table.currentEditor() 不存在
对不起,我的回答还有误。在 PyQT5 中,`QTableView` 并没有提供 `currentEditor()` 方法。可以通过 `QAbstractItemView` 的 `currentIndex()` 方法获取当前选中的单元格的索引,然后通过 `QAbstractItemView` 的 `indexWidget()` 方法获取该单元格的 editor。以下是正确的代码示例:
```python
index = table.currentIndex() # 获取当前选中的单元格的索引
editor = table.indexWidget(index) # 获取该单元格的 editor
if editor is not None:
table.closeEditor(editor, QtWidgets.QAbstractItemDelegate.NoHint)
```
其中,`table` 是 `QTableView` 的实例,`currentIndex()` 方法会返回当前选中的单元格的索引,如果没有选中任何单元格,则返回 `QModelIndex()`。`indexWidget()` 方法的参数是要获取的单元格的索引,返回该单元格的 editor,如果该单元格没有 editor,则返回 `None`。
需要注意的是,如果当前没有单元格处于编辑状态,该方法不会有任何效果。
pyqt5中,获取table表所有单元格的数据
可以使用以下代码获取QTableWidget中所有单元格的数据:
```python
# 获取行数和列数
rows = table.rowCount()
columns = table.columnCount()
# 遍历所有单元格并获取数据
data = []
for row in range(rows):
row_data = []
for column in range(columns):
item = table.item(row, column)
if item is not None:
row_data.append(item.text())
else:
row_data.append('')
data.append(row_data)
```
这里的`table`是一个QTableWidget对象,`data`是一个二维列表,包含了所有单元格的数据。你可以根据需要对代码进行修改。