QT 自定义model重写setHeaderData
时间: 2023-07-07 20:37:38 浏览: 53
在自定义的模型中,可以通过重写 `QAbstractItemModel` 的 `setHeaderData` 函数来自定义表头数据的设置。
下面是一个简单的例子:
```cpp
bool MyModel::setHeaderData(int section, Qt::Orientation orientation, const QVariant &value, int role)
{
if (role != Qt::EditRole) {
return false;
}
if (orientation == Qt::Horizontal) {
// 设置水平表头数据
// ...
emit headerDataChanged(orientation, section, section);
return true;
} else {
// 设置垂直表头数据
// ...
emit headerDataChanged(orientation, section, section);
return true;
}
}
```
在这个例子中,我们首先判断 `role` 是否为 `Qt::EditRole`,因为表头数据的修改操作一般都是通过这个 role 进行的。然后根据 `orientation` 参数来判断是设置水平表头还是垂直表头的数据。最后通过 `emit headerDataChanged` 发出表头数据修改信号,通知视图更新表头数据。
需要注意的是,重写 `setHeaderData` 函数时,还需要保证模型中对应的表头数据项是可编辑的,否则设置操作将会失败。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)