在QGraphicsItem QT中设置X Y坐标

问题描述 投票:0回答:1

[使用Qapplication和QGraphicsItem库确定对象的坐标,通常使用setPossetPos(mapToParent(yvelocity,-xvelocity))。这些命令的问题是它们确定对象移动的“速度”(而不是它们的X Y坐标!)。那么,通过什么命令我可以给X&Y输入,然后对象到达这些坐标?预先感谢。

qt qgraphicsscene qgraphicsitem qapplication
1个回答
0
投票
在我的评论中,我提出了建议:

类似于setPos(pos() + mapToParent(yvelocity,-xvelocity))。尽管pos()返回QPointF,但是您可以应用operator+。 -有适当的重载。

[三思而后行,我为mapToParent()感到挣扎,这对我来说似乎是错误的。

根据OP,速度描述了

方向。 mapToParent()专用于在父级局部坐标系中将局部position转换为position

因此,更好的建议可能是:

setPos(pos() + QPointF(yvelocity,-xvelocity));


我做了一个MCVE testQGraphicsItemSetPos.cc来证明这一点:

// Qt header: #include <QtWidgets> // main application int main(int argc, char **argv) { qDebug() << "Qt Version:" << QT_VERSION_STR; QApplication app(argc, argv); // setup data QGraphicsScene qGScene; QImage qImg("smiley.png"); QGraphicsPixmapItem qGItemImg(QPixmap::fromImage(qImg)); qGScene.addItem(&qGItemImg); const qreal v = 2.0; qreal xVel = 0.0, yVel = 0.0; // setup GUI QWidget qWinMain; qWinMain.resize(320, 200); qWinMain.setWindowTitle("QGraphicsView - Move Item"); QVBoxLayout qVBox; QGraphicsView qGView; qGView.setScene(&qGScene); qVBox.addWidget(&qGView, 1); qWinMain.setLayout(&qVBox); qWinMain.show(); // timer for periodic update using namespace std::chrono_literals; QTime qTime(0, 0); QTimer qTimerAnim; qTimerAnim.setInterval(50ms); // install signal handlers QObject::connect(&qTimerAnim, &QTimer::timeout, [&]() { // change velocity xVel and yVel alternating in range [-1, 1] const qreal t = 0.001 * qTime.elapsed(); // t in seconds xVel = v * std::sin(t); yVel = v * std::cos(t); // apply current velocity to move item qGItemImg.setPos(qGItemImg.pos() + QPointF(xVel, yVel)); }); // runtime loop qTimerAnim.start(); return app.exec(); }

CMakeLists.txt

project(QGraphicsItemSetPos) cmake_minimum_required(VERSION 3.10.0) set_property(GLOBAL PROPERTY USE_FOLDERS ON) set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_EXTENSIONS OFF) find_package(Qt5Widgets CONFIG REQUIRED) include_directories("${CMAKE_SOURCE_DIR}") add_executable(testQGraphicsItemSetPos testQGraphicsItemSetPos.cc) target_link_libraries(testQGraphicsItemSetPos Qt5::Widgets)

我用来在VS2017中构建并启动示例的方法:

snapshot of testQGraphicsItemSetPos.exe (animated)

© www.soinside.com 2019 - 2024. All rights reserved.