How to insert QPushButton into TableView?

▼魔方 西西 提交于 2020-01-29 14:29:32

问题


I am implementing 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 is shown with more information about this row.

Do you have any idea how to insert the button? I know about delegating system but all examples are only about "how to edit color with the combo box"...


回答1:


The model-view architecture isn't made to insert widgets into different cells, but you can draw the push button within the cell.

The differences are:

  1. It will only be a drawing of a pushbutton
  2. Without extra work (perhaps quite a bit of extra work) the button won't be highlighted on mouseover
  3. In consequence of #1 above, you can't use signals and slots

That said, here's how to do it:

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

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 model-view realm, use the views signals about selection and edits to popup your information window.




回答2:


You can use

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



回答3:


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



来源:https://stackoverflow.com/questions/2766873/how-to-insert-qpushbutton-into-tableview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!