pyqt中QtGui.QTableWidgetItem()改为双击可编辑
时间: 2024-03-04 18:45:12 浏览: 136
可以使用QTableWidget的setCellWidget()函数来设置一个QLineEdit部件作为单元格的持久编辑器,然后使用双击信号将其激活。具体步骤如下:
1.创建一个QLineEdit部件,并将其设置为单元格的持久编辑器:
```python
lineEdit = QLineEdit()
tableWidget.setCellWidget(row, column, lineEdit)
```
2.连接QTableWidget的cellDoubleClicked信号到一个槽函数:
```python
tableWidget.cellDoubleClicked.connect(self.editCell)
```
3.在槽函数中获取单元格的坐标,并将其持久编辑器设置为可编辑状态:
```python
def editCell(self, row, column):
lineEdit = self.tableWidget.cellWidget(row, column)
lineEdit.setReadOnly(False)
lineEdit.setFocus()
```
完整代码如下:
```python
from PyQt5.QtWidgets import QApplication, QTableWidget, QTableWidgetItem, QLineEdit
from PyQt5.QtCore import Qt
class MyTable(QTableWidget):
def __init__(self, rows, columns):
super().__init__(rows, columns)
self.initUI()
def initUI(self):
self.setHorizontalHeaderLabels(['Column 1', 'Column 2', 'Column 3'])
for i in range(self.rowCount()):
for j in range(self.columnCount()):
item = QTableWidgetItem('Item %d-%d' % (i, j))
self.setItem(i, j, item)
# 设置单元格持久编辑器
for i in range(self.rowCount()):
for j in range(self.columnCount()):
lineEdit = QLineEdit()
lineEdit.setReadOnly(True)
self.setCellWidget(i, j, lineEdit)
# 连接双击信号到槽函数
self.cellDoubleClicked.connect(self.editCell)
def editCell(self, row, column):
lineEdit = self.cellWidget(row, column)
lineEdit.setReadOnly(False)
lineEdit.setFocus()
if __name__ == '__main__':
app = QApplication([])
table = MyTable(4, 3)
table.show()
app.exec_()
```
阅读全文
相关推荐


















