QGraphicsView::QGraphicsView(QWidget *parent = nullptr)
QGraphicsView::QGraphicsView(QGraphicsScene *scene, QWidget *parent = nullptr)
- parent: 父控件,用于管理 QGraphicsView 的内存。
- scene: 要显示的场景。
- scene: 获取或设置 QGraphicsView 显示的场景。
- matrix: 获取或设置场景的变换矩阵。
- interactive: 获取或设置视图是否允许用户交互(如缩放、滚动)。
- setScene(QGraphicsScene *scene): 设置 QGraphicsView 要显示的场景。
- centerOn(const QPointF &point): 将视图中心移动到指定的点。
- scale(double factor): 对视图进行缩放。
- rotate(int degrees): 旋转视图。
- translate(int dx, int dy): 平移视图。
- sceneChanged(QGraphicsScene *scene): 当场景改变时发出的信号。
- sigStateChanged(QGraphicsView::ViewportUpdateMode mode): 当视图状态改变时发出的信号。
- void onSceneChanged(QGraphicsScene *scene): 通常用户自定义的槽函数,用于响应场景改变的事件。
- QGraphicsView::mapToScene(): 将视图坐标转换为场景坐标。
- QGraphicsView::mapFromScene(): 将场景坐标转换为视图坐标。
- QGraphicsItem::mapFromScene(): 将场景坐标转换为图元坐标。
- QGraphicsItem::mapToScene(): 将图元坐标转换为场景坐标。
- QGraphicsItem::mapToParent(): 将子图元坐标转换为父图元坐标。
- QGraphicsItem::mapFromParent(): 将父图元坐标转换为子图元坐标。
- QGraphicsItem::mapToItem(): 将当前图元坐标转换为另一个图元的坐标。
- QGraphicsItem::mapFromItem(): 将另一个图元的坐标转换为当前图元的坐标。
class MainWindow : public QWidget {
Q_OBJECT
public:
MainWindow() {
QGraphicsScene *scene = new QGraphicsScene(this);
scene->addRect(0, 0, 100, 100, QPen(), QBrush(Qt::blue));
QGraphicsView *view = new QGraphicsView(scene, this);
view->setRenderHint(QPainter::Antialiasing);
view->setInteractive(true);
QVBoxLayout *layout = new QVBoxLayout(this);
layout->addWidget(view);
}
};
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
MainWindow window;
window.show();
return app.exec();
}
class DraggableRect : public QGraphicsRectItem {
public:
DraggableRect(QGraphicsItem *parent = nullptr) : QGraphicsRectItem(0, 0, 100, 100, QPen(), QBrush(Qt::blue)) {
setPos(QPointF(50, 50)); // 初始位置
}
protected:
void mousePressEvent(QGraphicsSceneMouseEvent *event) override {
dragPosition = event->scenePos(); // 记录场景坐标系中的位置
QGraphicsRectItem::mousePressEvent(event);
}
void mouseMoveEvent(QGraphicsSceneMouseEvent *event) override {
QPointF delta = event->scenePos() - dragPosition; // 计算移动的距离
setPos(mapToParent(delta + pos())); // 更新位置
QGraphicsRectItem::mouseMoveEvent(event);
}
private:
QPointF dragPosition;
};
int main(int argc, char *argv[]) {
QApplication a(argc, argv);
QGraphicsScene scene;
scene.setSceneRect(0, 0, 800, 600); // 设置场景大小
DraggableRect *rect = new DraggableRect(); // 创建可拖动的矩形
scene.addItem(rect);
QGraphicsView view(&scene);
view.setRenderHint(QPainter::Antialiasing);
view.show();
return a.exec();
}
- 在 mousePressEvent 中,我们记录了鼠标按下时的场景坐标系中的位置。
- 在 mouseMoveEvent 中,我们计算了鼠标移动的距离,并使用 mapToParent 方法将这个距离转换为父坐标系中的位移,然后更新矩形的位置。
想了解更多
赶紧扫码关注
版权声明:
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若内容造成侵权、违法违规、事实不符,请将相关资料发送至xkadmin@xkablog.com进行投诉反馈,一经查实,立即处理!
转载请注明出处,原文链接:https://www.xkablog.com/rfx/36799.html