0

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();
    }
Dustin Sun
  • 5,292
  • 9
  • 49
  • 87

3 Answers3

1

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.

TheDarkKnight
  • 27,181
  • 6
  • 55
  • 85
  • Using `setPos` before `addItem` works fine. Qt docs are indeed not clear about it, but it seems that item position is stored in the item object and applied to it when it's added to a scene. – Pavel Strakhov Jul 06 '13 at 07:21
  • I've had problems in the past with setting the position first, but maybe that has since been fixed. I'll have a think about the problem a bit more. – TheDarkKnight Jul 06 '13 at 10:05
1

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 );
Shachi
  • 1,858
  • 3
  • 23
  • 41
0

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