pyqt5双击treeview节点之后,完成编辑,获取完成编辑得信号完整demo
时间: 2024-11-17 12:28:11 浏览: 9
PyQt5中的QTreeView通常用于显示数据树形结构,如果你想要在用户双击节点后触发编辑,然后在编辑完成后接收信号,你可以使用`QStandardItemModel`、`QTreeWidget`以及相关的槽函数。以下是一个简单的示例:
```python
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QTreeView, QStandardItemModel, QLineEdit, QVBoxLayout
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
# 创建模型
self.model = QStandardItemModel()
self.model.setHorizontalHeaderLabels(['Name', 'Value'])
# 添加一些初始数据
item_1 = QStandardItem('Item 1')
item_1.setEditable(True)
item_2 = QStandardItem('Item 2')
item_2.setEditable(True)
item_1.child(0) = QStandardItem('Child 1')
item_2.child(0) = QStandardItem('Child 2')
self.model.appendRow([item_1, QLineEdit()])
self.model.appendRow([item_2, QLineEdit()])
# 设置QTreeView
self.tree_view = QTreeView()
self.tree_view.setModel(self.model)
self.tree_view.doubleClicked.connect(self.edit_item)
layout = QVBoxLayout()
layout.addWidget(self.tree_view)
widget = QWidget()
widget.setLayout(layout)
self.setCentralWidget(widget)
def edit_item(self, index):
item = index.internalPointer()
if isinstance(item, QStandardItem):
if not item.isEditable():
return
line_edit = QLineEdit()
line_edit.setText(item.text())
line_edit.editingFinished.connect(self.on_text_changed(line_edit))
item.setData(line_edit)
item.setEditable(False)
line_edit.show()
def on_text_changed(self, line_edit):
text = line_edit.text()
current_index = line_edit.parent().indexFromItem(line_edit.parent())
self.model.setData(current_index, text)
line_edit.close()
item = current_index.internalPointer()
item.setEditable(True)
if __name__ == '__main__':
app = QApplication(sys.argv)
main_win = MainWindow()
main_win.show()
sys.exit(app.exec_())
阅读全文