How to insert QPushButton in TableView?

I am implementing a QAbstractTableModel and I would like to insert a QPushButton in the last column of each row. When users click on this button, a new window appears with additional information about this line.

Do you have an idea how to insert a button? I know about system delegation, but all the examples relate only to how to edit the color using the combo box ...

+4
source share
3 answers

The architecture of the model view is not designed to insert widgets into different cells, but you can draw a button inside the cell.

The differences are as follows:

  • It will only be a button drawing
  • Without additional work (perhaps quite a lot of additional work), the button will not be highlighted when you hover over
  • Due to # 1 above, you cannot use signals and slots

So here is how to do it:

Subclass QAbstractItemDelegate (or QStyledItemDelegate ) and implement the paint() method. To draw a button control (or any other control, for that matter), you need to use the style or method of QStylePainter::drawControl() :

 class PushButtonDelegate : public QAbstractItemDelegate { // TODO: handle public, private, etc. QAbstractItemView *view; public PushButtonDelegate(QAbstractItemView* view) { this->view = view; } void PushButtonDelegate::paint( QPainter* painter, const QStyleOptionViewItem & option, const QModelIndex & index ) const { // assuming this delegate is only registered for the correct column/row QStylePainter stylePainter(view); // OR: stylePainter(painter->device) stylePainter->drawControl(QStyle::CE_PushButton, option); // OR: view->style()->drawControl(QStyle::CE_PushButton, option, painter, view); // OR: QApplication::style()->drawControl(/* params as above */); } } 

Since the delegate keeps you within the viewing area of ​​the model, use signals of representations of choices and changes to pop up your information window.

+3
source

you can use

 QPushButton* viewButton = new QPushButton("View"); tableView->setIndexWidget(model->index(counter,2), viewButton); 
+5
source

You can use setCellWidget(row,column,QWidget*) to set the widget in a specific cell.

0
source

All Articles