QPushButton没有在QTableView上显示(使用QItemDelegate程序)

时间:2018-01-26 22:37:24

标签: c++ qt qt5 qtableview qitemdelegate

我有一个4行4列的QTableView。我试图仅向最后一列的所有单元格添加QPushButton,但第一行除外。当我运行我的代码时,我能够看到表格,但是当我点击4列的每个单元格时,我看到了QPushButton,但它立即消失了。只有单词" Detail"在QPushButton上仍然可见。我仍然在第一行看到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;
}                     

1 个答案:

答案 0 :(得分:1)

仅当您要编辑窗口小部件时才会调用

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();
}

enter image description here