Hello,

I am trying to create a custom Button of my own in Qt4. What I want it to do is to display an open switch and a closed switch respectively, depending on whether it has been pressed by the user. Like a QCheckBox, but with different graphics. Two possible solutions come to mind:

1.) Create a subclass of QAbstractButton.

I have tried to do this and have achieved some success, however I still have problems. For instance, I can display my own Button within another QWidget, but I cannot add it to any kind of layout (QGridLayout and the like). It is not visible then. I thought this could be a problem with the class I've written not being a subclass of QWidget but of QAbstractButton. But since QAbstractButton is a subclass of QWidget itself, I don't know what I am doing wrong here.
Here is the source code of my own Button class:

File: MyButton.h
Qt Code:
  1. #ifndef _MYBUTTON
  2. #define _MYBUTTON
  3. #include <QAbstractButton>
  4.  
  5. class MyButton : public QAbstractButton
  6. {
  7. Q_OBJECT
  8.  
  9. public:
  10. MyButton(QWidget *parent = 0);
  11. void paintEvent(QPaintEvent*);
  12.  
  13. signals:
  14. void valueChanged(int newValue);
  15. };
  16.  
  17. #endif
To copy to clipboard, switch view to plain text mode 

File: MyButton.cpp
Qt Code:
  1. #include "MyButton.h"
  2. #include <QtGui>
  3.  
  4. MyButton::MyButton(QWidget *parent)
  5. : QAbstractButton(parent)
  6. {
  7. setCheckable(true);
  8. setChecked(false);
  9. }
  10.  
  11. void MyButton::paintEvent(QPaintEvent*)
  12. {
  13. QPainter painter(this);
  14. QPen myPen;
  15. myPen.setWidth(2);
  16.  
  17. if(isChecked())
  18. {
  19. myPen.setColor(Qt::black);
  20. painter.setPen(myPen);
  21. painter.drawLine(20,29,50,20);
  22. int a = 1;
  23. emit valueChanged(a);
  24. }
  25. else
  26. {
  27. myPen.setColor(Qt::darkGray);
  28. painter.setPen(myPen);
  29. painter.drawLine(20,29,30,0);
  30. int b = 0;
  31. emit valueChanged(b);
  32. }
  33. painter.drawLine(0,30,20,30);
  34. painter.drawLine(50,30,70,30);
  35. painter.drawLine(50,30,50,20);
  36. }
To copy to clipboard, switch view to plain text mode 

2.) Another possibility would be to use the QCheckBox class and just change its graphical appearance by using QIcons. I tried that just a few minutes ago but somehow I can't seem to get it to display another pixmap. Here is a small example that does compile and run but obviously is not enough to change the QCheckBox's graphical appearance:

Qt Code:
  1. #include <QtGui>
  2.  
  3. int main(int argc, char *argv[])
  4. {
  5. QApplication app(argc, argv);
  6.  
  7. QCheckBox *button = new QCheckBox;
  8. button->setIcon(QIcon("CustomIcon.png"));
  9. button->show();
  10.  
  11. return app.exec();
  12. }
To copy to clipboard, switch view to plain text mode 

Any help on this matter is highly welcome. :-)