QPushButton setDown on click
Asked Answered
S

2

6

When a QPushButton is clicked, I want it to remain pressed down until clicked again.

void MainWindow::itemClicked(){

    QPushButton *clickedItem = qobject_cast<QPushButton *>(sender());

    qDebug() << clickedItem->isDown();

    if(!clickedItem->isDown())
        clickedItem->setDown(true);
    else
        clickedItem->setDown(false);
}

This doesn't seem to work. It will cause the button to be pressed down indefinitely.

clickedItem->isDown() is always false.

Scrapple answered 14/8, 2014 at 7:8 Comment(0)
T
7

isDown always returns false because you are checking it in a slot connected to the clicked signal. The clicked signal is emited when you press down the push button and release it. So every time the button is pressed and released the clicked signal is emited.

setCheckable() would work for you. It will make the button toggle. So when youu click, it'll stay in down state until you click it again.

Towers answered 14/8, 2014 at 10:0 Comment(0)
B
4

It should work out of the box using QAbstractButton::setCheckable(bool).

When set to true it should act the way you want it to act.

Berkeley answered 14/8, 2014 at 7:19 Comment(5)
Thanks, I know about setCheckable. I'm wondering why isDown doesn't work as expected.Scrapple
@МикроПингвин Probably because you do it in a slot which is connected to a clicked signal, and the button gets released before the slot is executed. That is why isDown always returns false.Lorenzalorenzana
How would I fix this? Would I need to implement a release slot?Scrapple
@МикроПингвин Why bother? Why not just use QAbstractButton::setCheckable?Lorenzalorenzana
as @Lorenzalorenzana mentioned, why not use a "checkable pushbutton" and if you need the state of the button ask for it using QAbstractButton::isChecked()Berkeley

© 2022 - 2024 — McMap. All rights reserved.