[英]attempted relative import beyond top-level package with boost/Python
[英]Positioning a top-level object relative to another
我需要放置一个顶层对象,以便它始终相对于另一个顶层对象保持位置。 例如,下图中的矩形应粘贴到椭圆的“前面”:
旋转180度时,它应如下所示:
而是,矩形的位置不正确:
请运行以下示例( QGraphicsScene
的使用仅出于演示目的,因为实际用例在物理学中)。
#include <QtWidgets>
class Scene : public QGraphicsScene
{
Q_OBJECT
public:
Scene()
{
mEllipse = addEllipse(0, 0, 25, 25);
mEllipse->setTransformOriginPoint(QPointF(12.5, 12.5));
QGraphicsLineItem *line = new QGraphicsLineItem(QLineF(0, 0, 0, -12.5), mEllipse);
line->setPos(12.5, 12.5);
mRect = addRect(0, 0, 10, 10);
mRect->setTransformOriginPoint(QPointF(5, 5));
line = new QGraphicsLineItem(QLineF(0, 0, 0, -5), mRect);
line->setPos(5, 5);
connect(&mTimer, SIGNAL(timeout()), this, SLOT(timeout()));
mTimer.start(5);
}
public slots:
void timeout()
{
mEllipse->setRotation(mEllipse->rotation() + 0.5);
QTransform t;
t.rotate(mEllipse->rotation());
qreal relativeX = mEllipse->boundingRect().width() / 2 - mRect->boundingRect().width() / 2;
qreal relativeY = -mRect->boundingRect().height();
mRect->setPos(mEllipse->pos() + t.map(QPointF(relativeX, relativeY)));
mRect->setRotation(mEllipse->rotation());
}
public:
QTimer mTimer;
QGraphicsEllipseItem *mEllipse;
QGraphicsRectItem *mRect;
};
int main(int argc, char** argv)
{
QApplication app(argc, argv);
QGraphicsView view;
view.setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
view.setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
view.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform);
view.setScene(new Scene);
view.resize(200, 200);
view.show();
return app.exec();
}
#include "main.moc"
请注意,矩形的位置并不总是相同的,但相对于椭圆,它应始终保持相同的位置。 例如,它可能从以下位置开始:
但是旋转时它应该保持在相对位置:
如果要使两个对象保持相同的相对位置,则它们需要围绕相同的原点旋转。
在这里,圆绕其中心(点12.5、12.5)旋转,但是矩形绕另一个原点(5,5)而不是圆的中心(12.5、12.5)旋转。
如果您固定了原点,它将按预期工作:
mRect->setTransformOriginPoint(QPointF(12.5, 12.5));
即使矩形以偏移量开始:
mRect = addRect(-10, 0, 10, 10); // Start 10 units to the left
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.