pyqt中tableWidget双击单元格失焦后获取单元格数据
时间: 2024-03-03 17:48:19 浏览: 87
使用pyqt5 tablewidget 单元格设置正则表达式
在PyQt中,可以通过以下步骤获取`QTableWidget`中双击单元格后失焦的单元格数据:
1. 连接单元格双击信号到相应的槽函数,槽函数可以在单元格失焦时被调用:
```python
self.tableWidget.cellDoubleClicked.connect(self.get_cell_data)
```
2. 在槽函数`get_cell_data`中,获取当前失焦的单元格的行号和列号:
```python
def get_cell_data(self, row, column):
self.current_row = row
self.current_column = column
```
3. 在单元格失焦后,通过行号和列号获取单元格数据:
```python
def focusOutEvent(self, event):
# 获取当前失焦的单元格的数据
item = self.tableWidget.item(self.current_row, self.current_column)
cell_data = item.text()
```
完整的代码示例:
```python
from PyQt5.QtWidgets import QApplication, QTableWidget, QTableWidgetItem, QWidget
from PyQt5.QtCore import Qt
class MyTableWidget(QTableWidget):
def __init__(self, rows, columns):
super().__init__(rows, columns)
self.current_row = None
self.current_column = None
self.init_ui()
def init_ui(self):
self.cellDoubleClicked.connect(self.get_cell_data)
self.setEditTriggers(QTableWidget.NoEditTriggers)
for i in range(self.rowCount()):
for j in range(self.columnCount()):
item = QTableWidgetItem(str(i) + str(j))
self.setItem(i, j, item)
def get_cell_data(self, row, column):
self.current_row = row
self.current_column = column
def focusOutEvent(self, event):
if self.current_row is not None and self.current_column is not None:
item = self.item(self.current_row, self.current_column)
cell_data = item.text()
print(cell_data)
self.current_row = None
self.current_column = None
if __name__ == '__main__':
app = QApplication([])
table = MyTableWidget(3, 3)
table.show()
app.exec()
```
运行该程序,双击单元格后失焦,即可在控制台输出对应单元格的数据。
阅读全文