4

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 ..

Niklas
  • 23,674
  • 33
  • 131
  • 170

2 Answers2

3

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

Marek R
  • 32,568
  • 6
  • 55
  • 140
  • I don't use an extra `QLabel`. I do use the one from `QCheckBox`. However I wanted to detect a click on that text, from `QCheckBox`. – Niklas Mar 01 '14 at 12:44
  • so what is wrong with [those signals](http://qt-project.org/doc/qt-5.0/qtwidgets/qabstractbutton.html#signals): `clicked(bool)`, `pressed()`, `released()`? Why did you accept answer with subclassing `QLabel` (this suggest that you use separate QLabel)? – Marek R Mar 02 '14 at 20:12
  • Cause: `I want to execute something and the checkstate should not be changed .. to checked or unchecked.` and thats not possible – Niklas Mar 02 '14 at 20:33
  • it is possible, event filter allows to lots of stuff without subclassing. I gave you a scratch of it, I'm pretty sure it requires improvement. Without details it is hard to tell what exactly you suppose to do. – Marek R Mar 02 '14 at 21:01
  • Thanks, I'll have a look at it. – Niklas Mar 03 '14 at 08:57
  • see an update, I'm pretty sure this is what you want. In other cases you should be able to tweak this to you needs. – Marek R Mar 04 '14 at 21:30
2

QLabel doesn't have an accessible 'on click' method, however you can subclass QLabel and reimplement the mousePressEvent(QMousePress *ev) slot which will allow you to do click detection.

Nicholas Smith
  • 11,642
  • 6
  • 37
  • 55