Search code examples
c++windowsqtqtablewidgetqcheckbox

Adjust QCheckbox into QTableWidget : Qt


I am facing issues when I adjust QCheckbox into QTableWidget.

It is working as expected in Mac and Linux but creating problem in Windows.

I have googled it and tried out different solutions, but it did not solve my problem.

Code:

QWidget* cellWidget = new QWidget();
QCheckBox *box = new QCheckBox();
box->setCheckState(Qt::Unchecked);
QHBoxLayout* layout = new QHBoxLayout(cellWidget);
layout->addWidget(box);
layout->setAlignment(Qt::AlignCenter);
layout->setContentsMargins(0, 0, 0, 0);
cellWidget->setLayout(layout);
ui->twidget_header->setCellWidget(0, 0, cellWidget);

Mac OS O/P : As Expected

enter image description here
Win OS O/P : Problem with Checkbox size and alignment

enter image description here .

My app is created in Qt 5.9 for Mac, Win and Linux platform. Let me know if you required more info about the problem.


Solution

  • The problem can happen with any QWidget while you create Qt app and support different resolutions.

    To overcome the size of the QWidget (QCheckbox/QRadiobutton), you just need to overwrite the QWidget class.

    Create customcheckbox.h file and overwrite the QCheckbox widget.

    class CustomCheckBox : public QCheckBox
    {
      Q_OBJECT
    public:
        CustomCheckBox(QWidget *parent=NULL);
    
    private:
        bool m_isChecked;
    
    public slots:
        void emitToggleSignal(bool);
    };
    

    Implement customcheckbox.cpp file as per your requirement.

    By doing this, QCheckbox will automatically adjust size on respective resolution.

    Hope this will save someone's time in future.

    Thanks.