Alexander Tomlinson
Alexander Tomlinson

Reputation: 13

Why my reimplementation of QCheckBox.hitButton works only for a small area of the check indicator?

I'm trying to reimplement the hitButton method of a QCheckBox, so that only the actual checkbox (i.e. not the label) is clickable. I'm not versed in C++, but looking at the source for QCheckBox, I tried to reimplement the existing code in python to see if I could then get it to work how I wanted.

My thought was that I would only have to change SE_CheckBoxClickRect to SE_CheckBoxIndicator. The below only seems to work in a very small area of the checkmark box, and nowhere else:

class ClickCheckBox(QCheckBox):
    """subclass to reimplement hitButton"""
    def __init__(self, *args):
        super(ClickCheckBox, self).__init__(*args)

    def hitButton(self, QPoint):
        style = QStyle.SE_CheckBoxClickRect
        opt = QStyleOptionButton()

        return QApplication.style().subElementRect(style, opt, self).contains(QPoint)

How can I make this work?

Upvotes: 1

Views: 266

Answers (1)

scopchanov
scopchanov

Reputation: 8419

Reimplementing QCheckBox.hitButton and replacing SE_CheckBoxClickRect with SE_CheckBoxIndicator is indeed the right approach to make only the check indicator clickable.

I have tested it in C++ and it works as expected:

bool CheckBox::hitButton(const QPoint &pos) const
{
    QStyleOptionButton opt;
    initStyleOption(&opt);

    return style()->subElementRect(QStyle::SE_CheckBoxIndicator, &opt, this).contains(pos);
}

Now, try to exactly translate that to Python, including the call to initStyleOption you are missing:

def hitButton(self, pos):
    opt = QStyleOptionButton()
    self.initStyleOption(opt)

    return self.style().subElementRect(QStyle.SE_CheckBoxIndicator, opt, self).contains(pos)

Upvotes: 1

Related Questions