12
for(int i=0; i<page.size(); i++){
    User user= Poco::AnyCast<User>(*it);
    ui.table->setItem(i,0,new QTableWidgetItem(user.userName)); 
    ui.table->setItem(i,1,new QTableWidgetItem(user.sex));
    ui.table->setItem(i,2,new QTableWidgetItem(user.age));

    QPushButton* btn_edit = new QPushButton();
    btn_edit = new QPushButton();
    btn_edit->setText("Edit");
    ui.table->setCellWidget(i,3,(QWidget*)btn_edit);

    ++it;
}

I add a QPushButton into the cell with the function setCellWidget(), I know, if it's a QTableWidgetItem, I can use :

ui.table->item(0,3)->setTextAlignment(QT::AlignHCenter)

But it is a Widget,

QTableWidgetItem item = ui.table->item(0,3); 

the item is null.

I can get the cell by use

ui.table->cellWidget(0,3).

How should I do to make the button centered in the cell?

2
  • You have memory leak here: QPushButton* btn_edit = new QPushButton(); btn_edit = new QPushButton(); (because this code allocated pair of buttons, but use only second of them)
    – Ilya
    Jul 23, 2014 at 11:36
  • @Ilya alright, that's a mistake…… thank you!
    – zack chen
    Jul 23, 2014 at 12:10

1 Answer 1

18

Try this:

QWidget* pWidget = new QWidget();
QPushButton* btn_edit = new QPushButton();
btn_edit->setText("Edit");
QHBoxLayout* pLayout = new QHBoxLayout(pWidget);
pLayout->addWidget(btn_edit);
pLayout->setAlignment(Qt::AlignCenter);
pLayout->setContentsMargins(0, 0, 0, 0);
pWidget->setLayout(pLayout);
ui.table->setCellWidget(i, 3, pWidget);
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.