c++ - QPushButton 未显示在 QTableView 上(使用 QItemDelegate 过程)

标签 c++ qt qt5 qtableview qitemdelegate

我有一个 4 行 4 列的 QTableView。我试图仅将 QPushButton 添加到最后一列的所有单元格(第一行除外)。当我运行代码时,我可以看到表格,但是当我单击第 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();
}

enter image description here

关于c++ - QPushButton 未显示在 QTableView 上(使用 QItemDelegate 过程),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48470550/

相关文章:

c++ - QDialog不在 parent 的中心

c++ - 使用 GDI 以图像为中心的黑色背景

c++ - 如何改善 Qt5 程序的启动时间?

xcode - 尝试在 OS X 上安装 Qt 给出 'You need to install Xcode 5.0.0' ,但这个版本太旧了,不可用

c++ - 在 OSX 10.8.3 上安装 Qwt 6.02 时出错

qt - CMake 和 Qt5 AUTOMOC 错误

c++ - 如何以编程方式获得 root 权限?

c++ - 我们可以将 Q_PROPERTY 与模板 <typename T> 一起使用吗?

c++ - 如何拦截Qt Quick qml事件?

qt - 如何在 Qt 中从 QToolBar 自定义 QToolButtons?