Turn QPolygon into a QPushbutton

225 Views Asked by At

I would like to paint a QPolygon on my Window and be able to use it as a QPushbutton. Is there any way to do this? (most preferably without using QMousePressEvent to check the position of the mouse with the position of the polygon)

After the advice of Ton:

MainWindow.cpp:

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    qv_point = {QPoint(10,20), QPoint(20,30), QPoint(50,30)};
    ui->pushButton = new QPolygonPushButton(qv_point);
    ui->setupUi(this);
    ui->pushButton->update();
}

MainWindow::~MainWindow()
{
    delete ui;
}

qpolygonpusbutton.cpp:

#include "qpolygonpushbutton.h"

QPolygonPushButton::QPolygonPushButton(QVector<QPoint> qv_points)
{
    this->polygon << qv_points;
}

void QPolygonPushButton::paintEvent(QPaintEvent *e)
{
    QPainter painter(this);
    painter.setViewport(e->rect());
    painter.setPen(QPen(Qt::black, 1, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
    painter.drawPolygon(this->polygon);
}
1

There are 1 best solutions below

2
Ton van den Heuvel On

This can be done by declaring your own push button type, something like QPolygonPushButton that derives from QPushButton, for which you then reimplement its paintEvent member function.

Something along the following lines (not tested):

class QPolygonPushButton : public QPushButton
{
public:
  using QPushButton::QPushButton;

private:
  void paintEvent(QPaintEvent* e) override
  {
     QPainter painter(this);
     painter.setViewport(e->rect());
     painter.drawPolygon(...);
  }
};

Update; fully working example. It uses a rectangle instead of a polygon but other than that you will get the idea. The button initially is a red rectangle, clicking it will change its color to blue.

#include <QtCore/QObject>
#include <QtGui/QApplication>
#include <QtGui/QMainWindow>
#include <QtGui/QPainter>
#include <QtGui/QPushButton>

namespace
{
  QColor buttonColor{Qt::red};
}

class QRectButton : public QPushButton
{
public:
  using QPushButton::QPushButton;

  void paintEvent(QPaintEvent* e) override
  {
    QPainter painter(this);
    painter.setPen(buttonColor);
    painter.setBrush(buttonColor);
    painter.drawRect(painter.window());
  }
};

class MainWindow : public QMainWindow
{
  Q_OBJECT

public:
  MainWindow() : QMainWindow(nullptr)
  {
    QPushButton* button{new QRectButton(this)};
    QObject::connect(button, SIGNAL(clicked()), this, SLOT(onButtonClicked()));
  }

private slots:
  void onButtonClicked()
  {
    buttonColor = Qt::blue;
    update();
  }
};

int main(int argc, char** argv)
{
  QApplication app(argc, argv);
  MainWindow window;
  window.show();
  return app.exec();
}

#include "moc_polygon_button.cpp"