问题描述
我正在尝试在更改组合框时更新我的模型。我有一个连接到更新模型的组合框的函数,但是来自 this question -“只要提供标准行为(访问 index.model()._data 不好),代表就应该使用模型的基本函数” .我还希望组合框的更改影响 QLineEdit 中出现的内容。
QItemDelegate:
class Delegate(QItemDelegate):
def __init__(self):
QItemDelegate.__init__(self)
self.type_items = ["1","2"]
def createEditor(self,parent,option,index):
if index.column() == 0:
comboBox = QComboBox(parent)
for text in self.type_items:
comboBox.addItem(text,(index.row(),index.column()))
comboBox.currentIndexChanged.connect(lambda: self.comboBoxChanged(comboBox,index))
return comboBox
return super().createEditor(parent,index)
# updates model but does not update view - shows what I want to happen
def comboBoxChanged(self,comboBox,index):
if comboBox.currentText() == "1":
index.model()._data[index.row()][0] = "1"
index.model()._data[index.row()][1] = "One"
elif comboBox.currentText() == "2":
index.model()._data[index.row()][0] = "2"
index.model()._data[index.row()][1] = "Two"
# self.dataChanged.emit(index,index) # can't call this here
QAbstractTableModel:
class TableModel(QAbstractTableModel):
def __init__(self,data):
super(TableModel,self).__init__()
self._data = data
def data(self,index,role):
if role in (Qt.DisplayRole,Qt.EditRole):
return self._data[index.row()][index.column()]
def rowCount(self,index=None):
return len(self._data)
def columnCount(self,index=None):
return len(self._data[0])
def flags(self,index):
return super().flags(index) | Qt.ItemIsEditable
def setData(self,value,role=Qt.EditRole):
if role == Qt.EditRole:
self._data[index.row()][index.column()] = value
self.dataChanged.emit(index,index)
return True
return False
主要内容:
class MainWindow(QMainWindow):
def __init__(self,parent=None):
super(MainWindow,self).__init__(parent)
localWidget = QWidget()
self.table = QTableView()
data = [["1","One"]]
self.model = TableModel(data)
self.table.setModel(self.model)
self.table.setItemDelegate(Delegate())
self.print_data = QPushButton("Print data")
self.print_data.clicked.connect(self.printData)
for row in range(self.model.rowCount()):
for column in range(self.model.columnCount()):
index = self.model.index(row,column)
self.table.openPersistentEditor(index)
layout_v = QVBoxLayout()
layout_v.addWidget(self.table)
layout_v.addWidget(self.print_data)
localWidget.setLayout(layout_v)
self.setCentralWidget(localWidget)
self.show()
def printData(self):
print(self.model._data)
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
- 如何在 qcombobox 中注册更改以正确更新模型? 和
- 如何使这触发 qlineedit 中的更改?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)