Search code examples
qtqtablewidgetqtablewidgetitemqcheckbox

QTableWidget with checkbox


I need to use QTableWidget with checkboxes instead of text in items. Checkbox must be in the center of item.

Examples which I tried work while checkbox is checked. If I uncheck checkbox it disapeares.


Solution

  • You can set the checkbox to be centered with this code:

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

    (I don't know if I understood you well here) And if you want to make your checkbox disappear when you uncheck it, you need to connect clicked signal of checkbox to a slot, that will make your checkbox invisible. Use connect method like this:

    connect(checkbox,SIGNAL(clicked()),this,SLOT(checkboxClicked()));
    

    You need to create slot checkboxClicked where you will be checking if the checkbox is checked or not. If not then you have to set it invisible. Example:

      QCheckBox* Chb = qobject_cast<QCheckBox *>(QObject::sender());
      if(!Chb->checked())
          Chb->setVisible(false);