Reputation: 3061
How can I create a QWidget
with a triangle shape?
It needs to be a QWidget
because it will be included inside another widget, must be clickable and will perform some animations (but at this first time I just need to create the triangle shape).
Something like this:
I'm using Qt 5.3
Upvotes: 3
Views: 854
Reputation: 4243
Here one example. hope it helps.
widget.h:
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QPainterPath>
#include <QPoint>
#include <QVector>
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = 0);
~Widget();
protected:
void paintEvent(QPaintEvent *event) override;
private:
QPainterPath getPath() const;
QRegion getRegion() const;
private:
int width = 100;
int height = 100;
QVector<QPoint> points;
};
#endif // WIDGET_H
widget.cpp:
#include "widget.h"
#include <QPainter>
#include <QPoint>
#include <QPainterPath>
#include <QBrush>
#include <QPolygon>
#include <QVector>
Widget::Widget(QWidget *parent)
: QWidget(parent),
points(3)
{
points[0] = QPoint(20, 20);
points[1] = QPoint(80, 20);
points[2] = QPoint(50, 80);
setFixedSize(width, height);
setMask(getRegion());
}
Widget::~Widget()
{
}
QPainterPath Widget::getPath() const
{
QPainterPath path;
path.moveTo(points[0]);
path.lineTo(points[1]);
path.lineTo(points[2]);
path.lineTo(points[0]);
return path;
}
QRegion Widget::getRegion() const
{
return QRegion(QPolygon(points));
}
void Widget::paintEvent(QPaintEvent *event)
{
Q_UNUSED(event);
QPainterPath path = getPath();
QPainter painter(this);
painter.setPen(Qt::NoPen);
painter.fillPath(path, QBrush(Qt::black));
}
Upvotes: 3