Add custom widget to QTableWidget cell

I have a custom widget created using a qt designer and I want to add it to a QTableWidget cell. But that does not work.

Here is the code:

int nRows =10;
for(int row = 0; row < nRows;row++;)

{
    QTableWidgetItem* item = new QTableWidgetItem();
    CustomWdg* wdg=new CustomWdg( );

    mTableWdg->insertRow( row );
    mTableWdg->setItem(row, 0, item);
    mTableWdg->setCellWidget( row, 0, wdg );

}  
+3
source share
2 answers

If you want to add a custom widget to a table cell, you can use QItemDelegate.

Create your own delegate class and inherit it from QItemDelegate.

class MyDelegate : public QItemDelegate
{
    public:
    CChoicePathDelegate (QObject *parent = 0);
    QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const; //delegate editor (your custom widget)
    void setEditorData(QWidget *editor, const QModelIndex &index) const;
    void setModelData(QWidget *editor, QAbstractItemModel *model,
    const QModelIndex &index) const; //transfer editor data to model
    void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option,
    const QModelIndex &index) const;
};

And then set the delegate for the table using these methods yourself.

setItemDelegate(QAbstractItemDelegate *)
setItemDelegateForColumn(int, QAbstractItemDelegate *)
setItemDelegateForRow(int, QAbstractItemDelegate *)

I tried this code:

#include "widget.h"
#include "ui_widget.h"
#include <QPushButton>
#include <QLabel>
#include <QHBoxLayout>

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    QHBoxLayout *l = new QHBoxLayout();
    l->addWidget((new QPushButton("I`m in cell")));
    l->addWidget((new QLabel("Test label")));

    QWidget *w = new QWidget();

    w->setLayout(l);

    ui->tableWidget->setCellWidget(1,1, w);
}

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

and the result:

Result

+4
source

, , , , setColumnCount(1) for. , , for ​​:

int nRows =10;
mTableWdg->setRowCount(nRows);
mTableWdg->setColumnCount(1);
for(int row = 0; row < nRows;row++;)

{
    //QTableWidgetItem* item = new QTableWidgetItem();// line one
    CustomWdg* wdg=new CustomWdg( );
    //mTableWdg->setItem(row, 0, item);// line three
    mTableWdg->setCellWidget( row, 0, wdg );

}  

item ( " 1" " " ), : QTableWidgetItem* item = new QTableWidgetItem("");, , CustomWdg setCellWidget

+3

All Articles