要在 QGraphicsView 中实现右键另存为图像功能,你可以按照以下步骤进行操作:

  1. 创建一个自定义的 QGraphicsView 子类,例如 MyGraphicsView。

  2. 在 MyGraphicsView 类的构造函数中,设置右键菜单策略为 Qt::CustomContextMenu,并连接 customContextMenuRequested 信号到一个自定义的槽函数,例如 showContextMenu。

MyGraphicsView::MyGraphicsView(QWidget *parent) : QGraphicsView(parent)
{
    setContextMenuPolicy(Qt::CustomContextMenu);
    connect(this, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(showContextMenu(const QPoint&)));
}
  1. 实现 showContextMenu 槽函数,该函数将在用户右键点击视图时被调用。在该函数中,创建一个 QMenu 对象,并添加一个 '另存为' 动作。
void MyGraphicsView::showContextMenu(const QPoint& pos)
{
    QMenu contextMenu(tr('Context Menu'), this);
    QAction saveAction('另存为', this);
    connect(&saveAction, SIGNAL(triggered()), this, SLOT(saveImage()));
    contextMenu.addAction(&saveAction);
    contextMenu.exec(mapToGlobal(pos));
}
  1. 实现 saveImage 槽函数,该函数将在用户点击 '另存为' 动作时被调用。在该函数中,使用 grab 方法获取视图的图像,并将其另存为文件。
void MyGraphicsView::saveImage()
{
    QString filePath = QFileDialog::getSaveFileName(this, '另存为', '', 'Images (*.png *.xpm *.jpg)');
    if (!filePath.isEmpty()) {
        QPixmap pixmap = this->grab();
        pixmap.save(filePath);
    }
}
  1. 在你的主窗口中,创建一个 MyGraphicsView 对象,并将其设置为主窗口的中心部件。
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent)
{
    MyGraphicsView *graphicsView = new MyGraphicsView(this);
    setCentralWidget(graphicsView);
}

这样,当用户在视图上右键点击时,将显示一个上下文菜单,其中包含一个 '另存为' 选项。点击 '另存为' 选项后,将弹出一个文件对话框,用户可以选择保存图像的路径和格式。选定路径后,视图的图像将被保存为文件。

Qt C++ 实现 QGraphicsView 右键另存为图像功能

原文地址: https://www.cveoy.top/t/topic/qz78 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录