PDA

View Full Version : How to add QPushButton to QTableWidget cell?



Gokulnathvc
15th April 2014, 07:05
QPushButton *btn1 = new QPushButton();
btn1->setParent(ui->tableStatus);
btn1->setIconSize((QSize(97,25)));
QPixmap* pixmap1 = new QPixmap("status.png");
QIcon icon1(*pixmap1);
btn1->setIcon(icon1);
btn1->setVisible(true);
ui->tableStatus->setCellWidget(0,3,btn1);

I have used the above code and it is not placing the button on the particular cell, It just attaches in the top left corner of the table widget.

ChrisW67
15th April 2014, 07:30
This code works just fine here but the table needs at least one row and four columns.

Line 4 is a memory leak.
Line 7 is unnecessary and results in the problem you describe if the table does not contain at least one row, four columns. The widget cannot be put in the cell but you have parented it and made it visible so it shows as a child of the table (i.e. on top of the table widget).

Gokulnathvc
15th April 2014, 07:35
I have already defined the row count as 16 and column count as 3 in constructor.

ChrisW67
15th April 2014, 07:53
Then you are not telling us what you are really doing:


#include <QApplication>
#include <QTableWidget>
#include <QPushButton>

int main(int argc, char *argv[])
{
QApplication app(argc, argv);

QTableWidget *tableStatus = new QTableWidget(4, 4);

// Your code
QPushButton *btn1 = new QPushButton();
btn1->setParent(tableStatus);
btn1->setIconSize((QSize(97,25)));
QPixmap* pixmap1 = new QPixmap("status.png");
QIcon icon1(*pixmap1);
btn1->setIcon(icon1);
btn1->setVisible(true);
tableStatus->setCellWidget(0,3,btn1);
// end of your code

tableStatus->show();

int ret = app.exec();
delete pixmap1;
delete tableStatus;
return ret;
}
10285
Or, if you change line 19 to:


tableStatus->setCellWidget(0,5,btn1); // non-existent cell

10286