Rotating a QWidget
Unsolved
General and Desktop
-
Hi,
I am trying to rotate a QWidget. I am already able to rotate a QPixmap using QPainter. I know you can't rotate a QLabel but how can I rotate a Qwidget or some container.
QPixmap pixmap(":/logo_new.png"); QPixmap rotate(pixmap.size()); QPainter p(&rotate); p.setRenderHint(QPainter::Antialiasing); p.setRenderHint(QPainter::SmoothPixmapTransform); p.setRenderHint(QPainter::HighQualityAntialiasing); p.translate(rotate.size().width()/2,rotate.size().height()/2); p.rotate(counter); p.translate(-rotate.size().width()/2,-rotate.size().height()/2); p.drawPixmap(0,0,pixmap); p.end();
-
it's not perfect (in fact I wouldn't say it works) but it's a start:
this will rotate 90 degrees anti-clockwise the widget you set in setBaseWidget#include <QWidget> #include <QPixmap> #include <QPainter> class RotateWidget : public QWidget { Q_OBJECT public: RotateWidget(QWidget *parent = nullptr): QWidget(parent){} virtual QSize sizeHint() const override{ const QSize origHint=m_baseWidget->sizeHint(); return QSize(origHint.height(),origHint.width()); } QWidget *baseWidget() const { return m_baseWidget; } void setBaseWidget(QWidget *baseWidget) { m_baseWidget = baseWidget; } protected: virtual void paintEvent(QPaintEvent * event) override{ if(!m_baseWidget) return QWidget::paintEvent(event); QPixmap basePixmap(m_baseWidget->size()); m_baseWidget->render(&basePixmap); QPainter p(this); p.setRenderHint(QPainter::Antialiasing); p.setRenderHint(QPainter::SmoothPixmapTransform); p.setRenderHint(QPainter::HighQualityAntialiasing); p.translate(m_baseWidget->width()/2,m_baseWidget->height()/2); p.rotate(-90); p.translate(-m_baseWidget->width()/2,-m_baseWidget->height()/2); p.drawPixmap(0,0,basePixmap); p.end(); } private: QWidget* m_baseWidget; };
for example:
#include <QApplication> #include <QLabel> #include "rotatewidget.h" int main ( int argc , char *argv[] ) { QApplication app(argc,argv); QLabel* tempLabel=new QLabel("Testing"); RotateWidget mainWid; mainWid.setBaseWidget(tempLabel); mainWid.show(); return app.exec(); }
-
Hi, Thanks for the reply. What I understand from your code is that you are doing a 90 degree rotation using width and height. But, a 90 degree rotation is anyway possible directly with a QLabel.
QMatrix rm; rm.rotate(90); pixmap = pixmap.transformed(rm); ui->Image->setPixmap(pixmap);
The problem is that I cannot rotate a qlabel by any other value between 0 and 90.