QPushButton 未显示在 QTableView 上(使用了 QItemDelegate 程序)

QPushButton is not showing on QTableView (QItemDelegate procedure used)

我有一个 4 行 4 列的 QTableView。我试图仅将 QPushButton 添加到最后一列的所有单元格,第一行除外。当我 运行 我的代码时,我能够看到 table 但是当我单击第 4 列的每个单元格时,我看到 QPushButton 但它立即消失。只有 QPushButton 上的单词 "Detail" 保持可见。而且我仍然在第一行看到 QPushButton。有任何想法吗?

这是buttoncolumndelegate.cpp

#include "buttoncolumndelegate.h"

ButtonColumnDelegate::ButtonColumnDelegate(QObject *parent) :
    QItemDelegate(parent)
{

}
QWidget * ButtonColumnDelegate::createEditor(QWidget *parent,
            const QStyleOptionViewItem &option,
            const QModelIndex &index) const
{
    QPushButton *detail = new QPushButton("Detail",parent);
    detail->setText("Detail");
    (void) option;
    (void) index;
    return detail;
}

void ButtonColumnDelegate::setEditorData(QWidget *editor,
                                     const QModelIndex &index) const
{
    QPushButton *detail = qobject_cast<QPushButton *>(editor);
    detail->setProperty("Detail", "Detail");
    detail->setText("Detail");
    (void) index;
}

void ButtonColumnDelegate::setModelData(QWidget *editor, QAbstractItemModel *model,
                                    const QModelIndex &index) const
{
    QPushButton *detail = qobject_cast<QPushButton *>(editor);
    model->setData(index, detail->property("Detail"));

}

void ButtonColumnDelegate::updateEditorGeometry(QWidget *editor,
                              const QStyleOptionViewItem &option,
                              const QModelIndex &index) const
{
    editor->setGeometry(option.rect);
    (void) index;  

这是dialog.cpp

#include "dialog.h"
#include "ui_dialog.h"
#include "buttoncolumndelegate.h"

Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{
    ui->setupUi(this);

    mybutton = new ButtonColumnDelegate(this);
    mModel = new QStandardItemModel(4,4,this);
    ui->tableView->setModel(mModel);
    ui->tableView->setItemDelegateForColumn(3, mybutton);

}

Dialog::~Dialog()
{
    delete ui;
}                     

createEditor() 仅在您要编辑小部件时调用,相反,如果您希望在不编辑值时显示按钮,则必须覆盖 paint() 方法

void ButtonColumnDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QPushButton button(index.data().toString());
    button.setGeometry(option.rect);
    painter->save();
    painter->translate(option.rect.topLeft());
    button.render(painter);
    painter->restore();
}