qtreeview添加QPushButton
时间: 2024-06-20 10:03:26 浏览: 11
在 QTreeView 中添加 QPushButton 可以通过重载 QStyledItemDelegate 类来实现。具体步骤如下:
1. 创建自定义代理类 CustomDelegate 继承自 QStyledItemDelegate。
2. 重载 createEditor 方法,用于创建自定义的编辑器,即 QPushButton。
3. 重载 setEditorData 方法,用于设置编辑器的初始值。
4. 重载 setModelData 方法,用于将编辑器中的值设置到 model 中。
5. 重载 updateEditorGeometry 方法,用于更新编辑器的位置和大小。
6. 在 QTreeView 中设置代理类为自定义代理类 CustomDelegate。
以下是示例代码,供您参考:
```
class CustomDelegate : public QStyledItemDelegate
{
public:
QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option,
const QModelIndex &index) const override
{
QPushButton *button = new QPushButton(parent);
button->setText("Button");
connect(button, &QPushButton::clicked, this, &CustomDelegate::commitAndCloseEditor);
return button;
}
void setEditorData(QWidget *editor, const QModelIndex &index) const override
{
// do nothing
}
void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const override
{
// do nothing
}
void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const override
{
editor->setGeometry(option.rect);
}
private slots:
void commitAndCloseEditor()
{
QPushButton *button = qobject_cast<QPushButton *>(sender());
emit commitData(button);
emit closeEditor(button);
}
};
```
在 QTreeView 中设置代理类为 CustomDelegate:
```
CustomDelegate *delegate = new CustomDelegate;
ui->treeView->setItemDelegate(delegate);
```
相关推荐
![](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)