I want axis labels for a plot I\'m making, and naturally the y-axis label should be oriented vertically. I\'m pretty sure QwtPlot
does this, but I\'m trying to
Here is a variant of Mostafa's implementation.
void VerticalLabel::paintEvent(QPaintEvent*)
{
QPainter painter(this);
// painter.translate(sizeHint().width(),0);
// painter.rotate(90);
painter.translate(0,sizeHint().height());
painter.rotate(270);
painter.drawText(QRect (QPoint(0,0),QLabel::sizeHint()),Qt::AlignCenter,text());
}
basically i have removed setPen and setBrush to preserve stylesheet and i have used an overload of drawText that uses the rect instead of point. This allows to have the '\n' inside the text or use WordWrap as a flag.
try using this:
#ifndef VERTICALLABEL_H
#define VERTICALLABEL_H
#include <QLabel>
class VerticalLabel : public QLabel
{
Q_OBJECT
public:
explicit VerticalLabel(QWidget *parent=0);
explicit VerticalLabel(const QString &text, QWidget *parent=0);
protected:
void paintEvent(QPaintEvent*);
QSize sizeHint() const ;
QSize minimumSizeHint() const;
};
#endif // VERTICALLABEL_H
///cpp
#include "verticallabel.h"
#include <QPainter>
VerticalLabel::VerticalLabel(QWidget *parent)
: QLabel(parent)
{
}
VerticalLabel::VerticalLabel(const QString &text, QWidget *parent)
: QLabel(text, parent)
{
}
void VerticalLabel::paintEvent(QPaintEvent*)
{
QPainter painter(this);
painter.setPen(Qt::black);
painter.setBrush(Qt::Dense1Pattern);
painter.rotate(90);
painter.drawText(0,0, text());
}
QSize VerticalLabel::minimumSizeHint() const
{
QSize s = QLabel::minimumSizeHint();
return QSize(s.height(), s.width());
}
QSize VerticalLabel::sizeHint() const
{
QSize s = QLabel::sizeHint();
return QSize(s.height(), s.width());
}
You can also create a new QGraphicsScene
, add to it QLabel and then rotate it. Like this:
QLabel* label = QLabel("Y axis");
QGraphicsScene scene;
QGraphicsProxyWidget * proxy = scene.addWidget(label);
proxy->rotate(-45);
QGraphicsView view(&scene);
view.show();
Take a look at the similar example (the output image has a wrong ratio, look at the direct URL).
So indeed I gave up on finding any simple way to achieve this, and looking over Uwe Rathmann's Qwt code indeed he uses QPainter::drawText()
in his QwtPainter::drawText
wrapper function, and a QTransform
to achieve the rotation, in QwtScaleDraw::labelTransformation
. So I've just put these together as follows:
void LabelWidget::paintEvent(QPaintEvent*)
{
QPainter painter(this);
painter.setPen(Qt::black);
//... Need an appropriate call to painter.translate() for this to work properly
painter.rotate(90);
painter.drawText(QPoint(0,0), _text);
}
Didn't need a QPixmap, it turns out.
There is no handy function in QLabel
to do what you want, no. So:
Use QGraphicsView
, which allows you to transform items however you want.
Use QPainter
. Probably the easiest approach would be to draw the text rotated into a QPixmap
, then set it on your QLabel
.