qtablewidget双击表格,弹出对话框后该表格修改数据
时间: 2024-03-19 21:20:09 浏览: 105
可以使用QTableWidget的itemDoubleClicked信号,连接一个槽函数,在该槽函数中弹出对话框进行数据修改,并在对话框中确认修改后将新的数据写回到该表格中。
下面是一个简单的示例代码:
```python
from PyQt5.QtWidgets import QApplication, QMainWindow, QTableWidget, QTableWidgetItem, QDialog, QVBoxLayout, QLineEdit, QPushButton
from PyQt5.QtCore import pyqtSignal
class MyDialog(QDialog):
def __init__(self, parent=None):
super(MyDialog, self).__init__(parent)
self.setWindowTitle('Edit Data')
self.setLayout(QVBoxLayout())
self.edit = QLineEdit()
self.btnSave = QPushButton('Save')
self.layout().addWidget(self.edit)
self.layout().addWidget(self.btnSave)
self.btnSave.clicked.connect(self.accept)
def setData(self, data):
self.edit.setText(data)
def getData(self):
return self.edit.text()
class MyTableWidget(QTableWidget):
itemChangedSignal = pyqtSignal(int, int, str)
def __init__(self, parent=None):
super(MyTableWidget, self).__init__(parent)
self.setColumnCount(2)
self.setRowCount(3)
self.setHorizontalHeaderLabels(['Name', 'Value'])
self.setItem(0, 0, QTableWidgetItem('A'))
self.setItem(0, 1, QTableWidgetItem('1'))
self.setItem(1, 0, QTableWidgetItem('B'))
self.setItem(1, 1, QTableWidgetItem('2'))
self.setItem(2, 0, QTableWidgetItem('C'))
self.setItem(2, 1, QTableWidgetItem('3'))
self.itemDoubleClicked.connect(self.onItemDoubleClicked)
def onItemDoubleClicked(self, item):
row = item.row()
col = item.column()
dlg = MyDialog(self)
dlg.setData(item.text())
if dlg.exec_():
newData = dlg.getData()
item.setText(newData)
self.itemChangedSignal.emit(row, col, newData)
class MainWindow(QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
tableWidget = MyTableWidget(self)
tableWidget.itemChangedSignal.connect(self.onItemChanged)
self.setCentralWidget(tableWidget)
def onItemChanged(self, row, col, data):
print('Item ({}, {}) changed to {}'.format(row, col, data))
if __name__ == '__main__':
app = QApplication([])
mainWindow = MainWindow()
mainWindow.show()
app.exec_()
```
在这个示例中,自定义了一个表格类MyTableWidget,继承自QTableWidget,并添加了一个itemChangedSignal信号,用于向外部发送数据修改的信号。在MyTableWidget中,连接了itemDoubleClicked信号到onItemDoubleClicked槽函数,该函数弹出对话框进行数据修改,并将新的数据写回到该表格中,同时发送itemChangedSignal信号。在MainWindow中,连接了MyTableWidget的itemChangedSignal信号到onItemChanged槽函数,该函数在控制台输出修改后的数据信息。
阅读全文