QStandardItemModel 单元格中添加widget
时间: 2024-05-17 17:18:50 浏览: 45
对于 QStandardItemModel,它是 Qt 框架中的一个模型类,用于在视图中显示和编辑数据。默认情况下,它只能在单元格中显示文本数据,无法直接添加 Widget。
如果你需要在 QStandardItemModel 的单元格中添加 Widget,一种常见的方法是使用自定义代理(QItemDelegate)来实现。你可以继承 QItemDelegate 类,并重写其 createEditor() 和 setEditorData() 方法来创建和设置自定义的 Widget。
以下是一个简单的示例代码,演示了如何在 QStandardItemModel 的单元格中添加一个 QPushButton:
```cpp
#include <QtWidgets>
class ButtonDelegate : public QItemDelegate
{
public:
QWidget* createEditor(QWidget* parent, const QStyleOptionViewItem& option, const QModelIndex& index) const override
{
if (index.column() == 0) { // 只在第一列添加按钮
QPushButton* button = new QPushButton(parent);
return button;
}
return QItemDelegate::createEditor(parent, option, index);
}
void setEditorData(QWidget* editor, const QModelIndex& index) const override
{
if (QPushButton* button = qobject_cast<QPushButton*>(editor)) {
button->setText(index.data(Qt::DisplayRole).toString());
}
else {
QItemDelegate::setEditorData(editor, index);
}
}
void setModelData(QWidget* editor, QAbstractItemModel* model, const QModelIndex& index) const override
{
if (QPushButton* button = qobject_cast<QPushButton*>(editor)) {
model->setData(index, button->text(), Qt::DisplayRole);
}
else {
QItemDelegate::setModelData(editor, model, index);
}
}
};
int main(int argc, char* argv[])
{
QApplication app(argc, argv);
QStandardItemModel model(4, 2);
QTableView tableView;
tableView.setModel(&model);
ButtonDelegate delegate;
tableView.setItemDelegate(&delegate);
for (int row = 0; row < model.rowCount(); ++row) {
for (int col = 0; col < model.columnCount(); ++col) {
QModelIndex index = model.index(row, col);
model.setData(index, "Button " + QString::number(row + 1));
}
}
tableView.show();
return app.exec();
}
```
在这个示例中,我们创建了一个自定义代理类 `ButtonDelegate`,并在 `createEditor()` 方法中创建了一个 QPushButton 对象,然后在 `setEditorData()` 方法中设置按钮的文本,`setModelData()` 方法中将按钮的文本保存到模型中。
最后,我们将这个自定义代理应用于 QStandardItemModel 的视图(QTableView),这样就可以在第一列的单元格中显示按钮了。
请注意,以上只是一个简单示例,实际应用中可能需要根据具体需求进行适当修改。希望对你有所帮助!
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)