将图像添加到QGraphicsScene中的某个位置

时间:2013-07-05 03:30:19

标签: c++ qt qgraphicsscene

我正在开发一个程序,允许用户选择一个文件并将其添加到QGraphicsView。除了项目定位之外,一切都可以正常工作。所有图像都显示在相同位置。源代码如下

//user action to add an image
    void MainWindow::on_actionMessage_triggered()
    {
        const int width = 150;
        const int height = 200;

        QString fileName = QFileDialog::getOpenFileName(this,"Open Image File",QDir::currentPath());

            QImage image(fileName);
            QGraphicsPixmapItem* item = new QGraphicsPixmapItem(QPixmap::fromImage(image));
            item->setScale(0.1);
            item->setFlags(QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsSelectable);
            item->setPos(scene->items.count()*width,scene->items.count()*height);
            scene->addItem(item);
    }


//initialize Scene
    MainWindow::MainWindow(QWidget *parent) :  QMainWindow(parent), ui(new Ui::MainWindow)
    {
        ui->setupUi(this);
        this->setBaseSize(800, 600);

        scene = new QGraphicsScene(0,0,600,400);
        scene->setSceneRect(0,0,600,400);

        ui->graphicsView->setScene(scene);
        //ui->graphicsView->fitInView(scene.sceneRect());
        ui->graphicsView->show();
    }

3 个答案:

答案 0 :(得分:1)

使用QGraphicsSystem时,您需要考虑在设置和检索项目位置时您正在影响的坐标系。

在这种情况下,一个没有父项的项目,而Qt文档声明没有父项将设置项目的场景坐标,它需要知道场景才能按照您的期望这样做。

因此,在调用setPos之前将项目添加到场景中。

答案 1 :(得分:0)

尝试使用mapToscene函数。例如:mapToscene(位置坐标)肯定会有效。

答案 2 :(得分:0)

我在这里分享了工作代码。

https://stackoverflow.com/a/45280054/1999190

此外,如果您希望默认位置位于顶部而不是中心,只需更改graphicsView的对齐方式。

 ui->graphicsView->setAlignment( Qt::AlignLeft | Qt::AlignTop );
相关问题