QTableWidget: center a checkbox inside a cell

QTableWidget is a very good control for show and manage data in a table format. It allow to insert inside cells different type of controls like listbox, checkbox and so on. In this post we'll discuss about the use of a checkbox control inside a cell with no text and the centering problem.



QTableWidget accept as standard cell content manager the QTableWidgetItem object. This object already have a settings for manage a checkbox control. You can insert a checkbox in a standard way by using the following code:

QTableWidgetItem *pItem = new QTableWidgetItem();
pItem->setCheckState(Qt::Checked);
pMyTableWidget->setItem(0,0,pItem);

As you can see in the image below the checkbox is showed but it is on the left side since the original idea is to have a checkbox and some text. If you don't provide any text the space is leaved empty.


Now if you are interested to have a cell with inside a checkbox control only (without any text) this way to paint the cell is not very good. The first solution to fix this problem is to create your own delegate object in charge to manage the centered paint of checkbox inside cell area. Is not a very difficult task and is possible to find a lot of working examples around. However put additional code just for center a control inside an area is not the best. Fortunately is there a workaround allowing to reach the same result but using only standard Qt widgets. The code is the following:

QWidget *pWidget = new QWidget();
QCheckBox *pCheckBox = new QCheckBox();
QHBoxLayout *pLayout = new QHBoxLayout(pWidget);
pLayout->addWidget(pCheckBox);
pLayout->setAlignment(Qt::AlignCenter);
pLayout->setContentsMargins(0,0,0,0);
pWidget->setLayout(pLayout);
pMyTableWidget->setCellWidget(0,0,pWidget);

You can see the result below:



The checkbox is centered. Hope that this will help.

Comments

Popular posts from this blog

Access GPIO from Linux user space

Android: adb push and read-only file system error

Tree in SQL database: The Nested Set Model