Reputation: 5532
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();
}
Upvotes: 1
Views: 9600
Reputation: 1888
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 );
Upvotes: 2
Reputation: 1
try to use mapToscene function. ex: mapToscene(Position Coordinates) it will definitely work.
Upvotes: 0
Reputation: 27611
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.
Upvotes: 1