QTTablewidget 某一列设置为下拉框并设置默认值
时间: 2023-09-01 16:13:45 浏览: 134
tableWidget添加按钮,添加下拉框,控件合并拆分
要将QTTableWidget中的某一列设置为下拉框并设置默认值,可以通过自定义QComboBox委托实现。下面是一个示例代码:
```python
from PyQt5.QtWidgets import QComboBox, QTableWidgetItem, QTableWidget, QApplication, QWidget, QHBoxLayout, QTableWidgetItem, QStyledItemDelegate
class ComboBoxDelegate(QStyledItemDelegate):
def __init__(self, choices=[], parent=None):
super().__init__(parent)
self.items = choices
def createEditor(self, parent, option, index):
editor = QComboBox(parent)
editor.addItems(self.items)
return editor
def setEditorData(self, editor, index):
value = index.data()
editor.setCurrentIndex(editor.findText(value))
def setModelData(self, editor, model, index):
value = editor.currentText()
model.setData(index, value, 0)
class MyTableWidget(QTableWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.setColumnCount(2)
self.setHorizontalHeaderLabels(['Name', 'Gender'])
self.setItemDelegateForColumn(1, ComboBoxDelegate(["Male", "Female"], self))
self.setRowCount(1)
self.setItem(0, 0, QTableWidgetItem("Tom"))
self.setItem(0, 1, QTableWidgetItem("Male"))
if __name__ == '__main__':
app = QApplication([])
widget = MyTableWidget()
widget.show()
app.exec_()
```
在上述代码中,我们首先定义了一个自定义的QStyledItemDelegate,它继承自QStyledItemDelegate,并重写了createEditor、setEditorData和setModelData方法,分别用于创建下拉框、设置下拉框的默认值和将下拉框的值更新到数据模型中。
然后,在MyTableWidget中,我们将第二列设置为ComboBoxDelegate,并将其选项设置为["Male", "Female"],这样就将第二列设置为了下拉框,并且默认值为"Male"。
阅读全文