Add a QPushButton into a QTableWidgetItem in a QTableWidget, How to make it Qt::AlignHCenter

我的未来我决定 提交于 2019-12-04 21:26:19

问题


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?


回答1:


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);


来源:https://stackoverflow.com/questions/24909322/add-a-qpushbutton-into-a-qtablewidgetitem-in-a-qtablewidget-how-to-make-it-qt

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