0

I am very new to QT development. Can anyone share "How to create a custom QPushButton in QT" so that custom button will have same behavior as of QPushButton only differ from custom properties. So please any clue or any direction to this will be helpful. I have tried for the Analog Clock example which is given in QT custom widget example. But I didn't find related with QPushbutton. Thanks in advance.

Avi
  • 31
  • 2
  • 7
  • 1) First of all you have to start from subclassing a qpusbutton class. 2)Than you have to use google to find this [video](https://www.youtube.com/watch?v=whgZ0iKztIo) – Bob Oct 19 '16 at 12:16

1 Answers1

1

Its very simple. First you need to subclass QPushButton. Add your methods to enhance it. And you are done.

For example, I have written CustomButton which have an extra method to reverse the text.

CustomButton.h

#ifndef CUSTOMBUTTON_H
#define CUSTOMBUTTON_H

#include <QPushButton>

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

    // Enhancement, it will reverse the button text
    void reverseText();
};

#endif // CUSTOMBUTTON_H

CustomButton.cpp

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

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

}

void CustomButton::reverseText()
{
    QString buttonText = text();
    std::reverse(buttonText.begin(), buttonText.end());
    setText( buttonText );
}

main.cpp

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

The button looks like this enter image description here

If you want to do something related to look and feel. Instead of creating custom button you can use QStyleSheet

sanjay
  • 735
  • 1
  • 5
  • 23
  • Thanks for the solution but I will be more appreciated if you explain/suggest how to use this custom button as new widget plugin and call in other project with all its custom methods say in this case reverse method. – Avi Oct 20 '16 at 04:52
  • It will behave like any other widget. What do you mean by Plugin? are you talking about QtCreator Designer plugin? – sanjay Oct 20 '16 at 05:49
  • Yes, QtCreator Designer Plugin that too using painter class for creating button and not using StyleSheet. – Avi Oct 20 '16 at 06:59