简体   繁体   中英

Add an Image to certain position in QGraphicsScene

I am developing a program to allow users to select a file and add it to QGraphicsView. Everything esle works fine except item-positioning. All images are displayed in the same position. Source code is as below

//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();
    }

When using the QGraphicsSystem you need to think about which coordinate system you're affecting when setting and retrieving an item's position.

In this case of an an item that has no parent and while the Qt docs states that with no parent it will set the scene coordinates of the item, it would require knowledge of the scene to do that as you're expecting.

Therefore, add the item to the scene before calling setPos.

try to use mapToscene function. ex: mapToscene(Position Coordinates) it will definitely work.

I shared the working code here.

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

Also,if you want the default position at top, instead of center,simply change the alignment of graphicsView.

 ui->graphicsView->setAlignment( Qt::AlignLeft | Qt::AlignTop );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM