Search code examples
c++qtqwidgetqpushbutton

Customise button in QT


I need to create a toggle button in qt and it should look like the below image. It should show the ON image when it is turned on and remain at this state until it is toggled again. It should show the OFF image in the off case. Please help me on this.

enter image description here

enter image description here


Solution

  • You can use images as an icon (sadly, it won't scale with button by default), create a class which would paint those images in the handler for paint event, or you can use those images in QSS stylesheet. QSS is CSS 2.0 analog for Qt's GUI elements.

    Note that after using stylesheet all changes to visuals of said element should be done through changes to stylesheet as well.

    THose styles can be set through form editor by right-clicking a widget and choosing "Change stylesheet" or through code directly by calling setStyleSheet, depending which workflow you prefer.

    button->setStyleSheet(
        "QPushButton {  border-image: url(:/Resources/chbUnchecked.png); }"
        "QPushButton::checked { border-image: url(:/Resources/chbChecked.png); }" );
    

    border-image Scales image to border limits, replacing standard border.There is also a background-image which fills widget's surface with regular repeats.

    To limit this change only for checkable buttons:

    button->setStyleSheet(
        "QPushButton[checkable="true"] {    border-image: url(:/Resources/chbUnchecked.png); }"
        "QPushButton::checked[checkable="true"] {   border-image: url(:/Resources/chbChecked.png); }" );
    

    :/Resources/ is a path within app's resources.

    QSS syntax: https://doc.qt.io/Qt-5/stylesheet-syntax.html

    Note that QSS have selectors, so it's it have same "Cascading" ability as CSS. You can assign styles bulk based on hierarchical location on GUI, class-inheritances, class names, quasi-states and names.

    If you set style above to a window, all instances of QPushButton within that window would have said style. If you define a new class for such Button, you can use its name instead of standard button class, although QSS for base class would apply to it.