pyqt6 QTableView 显示字典
时间: 2024-01-12 13:04:52 浏览: 169
可以使用 QStandardItemModel 来显示字典数据。
下面是一个简单的示例代码:
```python
from PyQt6.QtCore import Qt, QAbstractTableModel, QVariant
from PyQt6.QtGui import QStandardItemModel, QStandardItem
from PyQt6.QtWidgets import QApplication, QTableView
class DictTableModel(QAbstractTableModel):
def __init__(self, data):
super().__init__()
self._data = data
def rowCount(self, parent):
return len(self._data)
def columnCount(self, parent):
return 2
def data(self, index, role):
if role == Qt.ItemDataRole.DisplayRole:
row, col = index.row(), index.column()
key = list(self._data.keys())[row]
value = list(self._data.values())[row]
if col == 0:
return QVariant(key)
elif col == 1:
return QVariant(value)
return QVariant()
app = QApplication([])
data = {"name": "Alice", "age": 25, "gender": "female"}
table_model = DictTableModel(data)
table_view = QTableView()
table_view.setModel(table_model)
table_view.show()
app.exec()
```
这个例子中,我们定义了一个名为 `DictTableModel` 的类,该类继承自 `QAbstractTableModel`。在 `DictTableModel` 类中,我们实现了 `rowCount`、`columnCount` 和 `data` 方法,用于设置表格的行数、列数和单元格数据。
在 `data` 方法中,我们使用给定索引 `index` 获取相应的字典键和值,并根据单元格的列数返回相应的数据。
最后,我们将 `DictTableModel` 实例设置为 `QTableView` 的模型,并显示 `QTableView`。
运行上述代码,将会在屏幕上显示一个带有三行两列的表格,其中第一列显示字典的键,第二列显示字典的值。
阅读全文
相关推荐


















