以QGraphicsRectItem为例,需要让显示的矩形绕矩形中心旋转,需要用到setTransformOriginPoint以及setRotation函数。
代码如下:
#include "widget.h"
#include "ui_widget.h"
#include <QGraphicsScene>
#include <QGraphicsRectItem>
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
QGraphicsScene *scene = new QGraphicsScene;
//-2是为了不显示scrollbar
scene->setSceneRect(0, 0, ui->view->width()-2, ui->view->height()-2);
ui->view->setScene(scene);
for(int i=0; i<4; i++)
{
QGraphicsRectItem *item = new QGraphicsRectItem;
item->setPen(QPen(QColor("red")));
item->setPos(QPointF(scene->width()/2, scene->height()/2));
item->setRect(0, 0, scene->width()/4, scene->width()/4);
scene->addItem(item);
}
int i=0;
for(auto &item : scene->items())
{
auto rect = item->boundingRect();
item->setTransformOriginPoint(QPointF(rect.x(), rect.y())+QPointF(rect.width()/2, rect.height()/2));
item->setRotation(i++*15);
}
}
Widget::~Widget()
{
delete ui;
}
效果图: