Solved how to create an icon button with separate visual up and down state?
-
using Qt Widgets, C++ app
I'd expect i can create a QIcon with up and down states (selected? active?), then set that into a push button or tool button, but no, that doesn't work. when the user clicks in the button, no separate image is drawn.
how do i simply create a button that draws a different image while in its down state? is there sample code?
i've googled A LOT and found nothing simple. looking at the paintEvent() of QToolButton, it calls into drawComplexControl() and imagining re-implementing all that makes my head spin.
-
okay wow it wasn't THAT hard. I override QToolButton with this:
void QIconButton::paintEvent(QPaintEvent *e) { QPainter painter(this); QIcon icon(_inherited::icon()); QRect frameR(QPoint(0, 0), iconSize()); QIcon::Mode mode = QIcon::Normal; if (isDown()) { mode = QIcon::Active; } icon.paint(&painter, frameR, Qt::AlignCenter, mode); }
-
This is custom enough that I believe you would most likely need to subclass QAbstractButton and provide your own paint events...so "simply" is very relative in this case.
-
@davecotter You could set different icons in https://doc.qt.io/qt-5/qabstractbutton.html#pressed (down/pressed state) and https://doc.qt.io/qt-5/qabstractbutton.html#released (up/released state).
-
@jsulm how?
-
By using stylesheet.
myButton->setStyleSheet("QPushButton#myButton:pressed { border-image: ..... }"); // Same for any other state
More examples here (https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qpushbutton)
-
@davecotter said in how to create an icon button with separate visual up and down state?:
how?
What about https://doc.qt.io/qt-5/qabstractbutton.html#icon-prop ?
Or stylesheets as @Pl45m4 suggested -
okay wow it wasn't THAT hard. I override QToolButton with this:
void QIconButton::paintEvent(QPaintEvent *e) { QPainter painter(this); QIcon icon(_inherited::icon()); QRect frameR(QPoint(0, 0), iconSize()); QIcon::Mode mode = QIcon::Normal; if (isDown()) { mode = QIcon::Active; } icon.paint(&painter, frameR, Qt::AlignCenter, mode); }