0

I was trying to understand if there is a way to build a particular customized QPushButton?

What I am trying to achieve is the following layout and appearance:

The button is shown below, notice the red line (which meas that the button is not clicked). I am not sure how to achieve the red line. I think it could be widget? or a QProgressbar, that when is clicked goes/loads up to green..I am not sure because I don't have enough experience and have been trying to build it. However this seems to be a bit tough:

bt

And below how it should look like right after the click happened (note the green line):

bt2

Despite my efforts, I found some useful sources that I could use to get me started: for example this source was great to understand how to start. I studied the fact that in order to achieve that, the button need to be subclassed, and that is great because it lays some sort of route. Below the code I used:

custombutton.h

#ifndef CUSTOMBUTTON_H
#define CUSTOMBUTTON_H

#include <QPushButton>

class CustomButton : public QPushButton
{
public:
    CustomButton( const QString& text, QWidget* parent = 0 );
    void writeText();
};

#endif // CUSTOMBUTTON_H

custombutton.cpp

#include "CustomButton.h"
#include "algorithm"

CustomButton::CustomButton( const QString& text, QWidget* parent )
    : QPushButton( text, parent )
{

}

void CustomButton::writeText()
{
    QString buttonText = text();
    setText( buttonText );
}

main

#include <QApplication>
#include "CustomButton.h"
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    CustomButton w( "MyButton" );
    w.show();
    w.writeText();
    a.exec();
    return 0;
}

Another useful source I found is this one which also was useful.

The official documentation points to use the styles, but I am trying not to do that because I would like to solve the problem understanding what is the potential of subclassing with Qt. Unless going in the style direction is the only possible way to solve this problem? I would like to thank anyone in advance for sharing or pointing to a potential solution on how to do that.

EsoMars
  • 337
  • 3
  • 14

1 Answers1

0

You can set your button as checkable and then set a different icon for the 2 states. In your case you'd have to set the red icon for the Normal mode and the green one for the Selected mode

Different icons for different states

Here's an example:
https://www.dropbox.com/s/x40byuyu2ph8m1y/CheckableButton.zip?dl=0
Here someone asked the same thing:
https://forum.qt.io/topic/72363/change-icon-of-pushbutton
Here you can read abouth the modes:
https://doc.qt.io/qt-5/qicon.html#Mode-enum

PS: Of course overriding QAbstractButton::paintEvent(QPaintEvent *event) is a viable option too

Jack Lilhammers
  • 1,207
  • 7
  • 19