Add QPushButton to QTableWidgetItem in QTableWidget, how to do QT :: AlignHCenter

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 to the cell using the setCellWidget () function. I know if this is a QTableWidgetItem, I can use:

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

But this is a widget,

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

element is null.

I can get the cell using

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

How to make the button centered in the cell? Thanks!

+6
source share
1 answer

Try the following:

 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); 
+8
source

Source: https://habr.com/ru/post/972700/


All Articles