c++ - Positioning a top-level object relative to another -
i need position top-level object remains in position relative top-level object. example, rectangle in image below should stick "front" of ellipse:
when rotated 180 degrees, should this:
instead, position of rectangle incorrect:
please run example below (the use of qgraphicsscene
demonstration purposes only, actual use case in physics).
#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"
note position of rectangle not same, should remain in same position relative ellipse. example, may start off in position:
but should stay in relative position when rotated:
if want 2 objects keep same relative position, need rotate around same origin point.
here circle rotates around center (the point 12.5, 12.5), rectangle rotates around origin (5,5) instead of circle's center (12.5, 12.5).
if fix origin, it'll work expect:
mrect->settransformoriginpoint(qpointf(12.5, 12.5));
even if rectangle starts off offset:
mrect = addrect(-10, 0, 10, 10); // start 10 units left
Comments
Post a Comment