Search code examples
c++qtsignals-slotsqcheckbox

QCheckBox detect click on label


Is there any way to detect if the user clicked on the label on a QCheckBox or not? If so, I want to execute something and the checkstate should not be changed .. to checked or unchecked.

So far I can not find any signals / ways for that ..


Solution

  • Event filter is the answer.

    First install event filter on a check box for which you want to change behavior (during construction):

    ui->checkBox->installEventFilter(this);
    

    and then reject mouse press event when mouse is over the label (note how label is localized in code):

    bool MainWindow::eventFilter(QObject *o, QEvent *e)
    {
        if (o==ui->checkBox) {
            QMouseEvent*mouseEvent = static_cast<QMouseEvent*>(e);
            if (e->type()==QEvent::MouseButtonPress &&
                    mouseEvent->button()==Qt::LeftButton) {
                QStyleOptionButton option;
                option.initFrom(ui->checkBox);
                QRect rect = ui->checkBox->style()->subElementRect(QStyle::SE_CheckBoxContents, &option, ui->checkBox);
                if (rect.contains(mouseEvent->pos())) {
                    // consume event
                    return true;
                }
            }
            return false;
        }
        return QMainWindow::eventFilter(o,e);
    }
    

    I've test it on Qt 4.8.1 for Linux and it works as you want (mouse clicks on a label are ignored and on check box it toggles state of check box).