QTreeView显示复选框
时间: 2023-08-27 13:06:11 浏览: 94
要在 QTreeView 中显示复选框,您可以通过以下步骤进行设置:
1. 创建一个 QStandardItemModel 对象,并将其设置为 QTreeView 的数据模型:
```cpp
QStandardItemModel* model = new QStandardItemModel;
treeView->setModel(model);
```
2. 在创建 QStandardItem 对象时,将其标志设置为 `Qt::ItemIsUserCheckable`,并根据需要设置初始的复选框状态:
```cpp
QStandardItem* item = new QStandardItem("Item 1");
item->setFlags(item->flags() | Qt::ItemIsUserCheckable);
item->setCheckState(Qt::Unchecked); // 设置初始复选框状态
model->appendRow(item);
```
3. 可以通过调用 `setItemDelegate()` 函数,为 QTreeView 设置一个 QStyledItemDelegate 对象,以确保复选框正确绘制:
```cpp
treeView->setItemDelegate(new QStyledItemDelegate);
```
现在,当您运行应用程序并查看 QTreeView 时,您将看到每个项目旁边都有一个复选框。用户可以单击复选框来切换其状态。
请注意,上述示例适用于使用 QStandardItemModel 的情况。如果您使用的是自定义的数据模型(例如继承自 QAbstractItemModel),则需要相应地实现 `flags()` 和 `setData()` 方法,以便支持复选框的显示和状态切换。
相关推荐
![](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)