Adding button to QTableview

前端 未结 6 1661
遥遥无期
遥遥无期 2020-12-14 10:57

I have created one table by using QTableview and QAbstractTableModel . In one of the cells, I want to add one help button in the r

6条回答
  •  情歌与酒
    2020-12-14 11:51

    I've got a solution WITHOUT any complex re-invention of the whole paint-processes. I have a TableView in which I have a button in every row. Note, that, in my case the for loop runs through each row.

    QSignalMapper *signalMapper = new QSignalMapper(this);
    
    for( int i=0; iindex(i, COLUMN_FOR_WHATEVER_YOU_WANT);
         model->setData(item, QVariant::fromValue(yourObject.getSpecificInformation()));
    
         //make new button for this row 
         item = model->index(i, COLUMN_BUTTON); 
         QPushButton *cartButton = new QPushButton("Add");
         ui->table_view->setIndexWidget(item, cartButton);
    
         signalMapper->setMapping(cartButton, i);
         connect(cartButton, SIGNAL(clicked(bool)), signalMapper, SLOT(map()));
    }
    connect(signalMapper, SIGNAL(mapped(int)), this, SLOT(doSomething(int)));
    

    Then you automatically get the index of the row in which the user clicked the button. You just need to make your own slot:

    private SLOTS:
        void doSomething(int row);
    

    If you have specific cells, it would work similar.

    Note, that I did not care about memory leaks in this example, and I don't exactly know what would happen if you update your TableView... (It's working fine, but it might not delete the old button-pointers when new ones are created)

提交回复
热议问题