Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vertical QLabel, or the equivalent?

Tags:

c++

qt

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 keep things light so I'm just using a simple QWidget + QPainter for now. I didn't see any way to change QLabel orientation in the documentation. Some solutions are given in this 2002 thread but I'd like something that doesn't seem like such a hack. I'm using Qt 4.8 now, is there really no way to do this aside from QPainter::drawText()?

like image 458
Matt Phillips Avatar asked Feb 07 '12 20:02

Matt Phillips


1 Answers

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());
}
like image 56
Mostafa Avatar answered Oct 24 '22 09:10

Mostafa