Search code examples
c++qtviewmodel

Qt set a custom widget inside a QTableView


I need to put a custom widget inside a QTableView cell from a subclassed QAbstractTableModel.

I searched for already given solutions but no one catch my needs. The custom widget must stay here all the time and not only in editing mode like with the QItemDelegate::createEditor. The custom widget may be everything, i'm searching for a general solutions for all the widget not only QPushButtons or QCheckBox.

Sorry for my english.


Solution

  • You can use QAbstractItemView::setIndexWidget and overriding QAbstractItemView::dataChanged to achieve what you want as follows:

    class MyTableView : public QTableView
    {
    protected:
      void dataChanged(const QModelIndex &topLeft, const QModelIndex & bottomRight, const QVector<int> & roles)
      {
        QPushButton *pPushButton = qobject_cast<QPushButton*>(indexWidget(topLeft));
        if (pPushButton)
            pPushButton->setText(model()->data(topLeft, Qt::DisplayRole).toString());
        else
            QTableView::dataChanged(topLeft, bottomRight, roles);
      }
    };
    
    void main ()
    {
        MyTableView table;
        table.setIndexWidget(table.model()->index(0, 0, QModelIndex()),new QPushButton());
    }
    

    Note that it is an incomplete implementation, but it should show you how you can solve your problem. A real implementation should update all QPushButton between topLeft and bottomRight.