Set an image for QGraphicsRectItem
Solved
General and Desktop
-
I want to set a 24*24px PNG image for a QGraphicsRectItem on a QGraphicsScene/View
I tried the following:scene = new QGraphicsScene(this); view= new QGraphicsView(this); view->setScene(scene); view->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); view->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); setCentralWidget(view); QBrush q; q.setTextureImage(QImage("resources/list.png")); QGraphicsRectItem* d = new QGraphicsRectItem; d->setRect(30,30,24,24); d->setBrush(q); scene->addItem(d);
But it doesn't look as expected:
The image is not centered in the RectItem and also appears 2x partially...
Also I'm not sure if setTextureImage() is a good way to set an image -
I want to set a 24*24px PNG image for a QGraphicsRectItem on a QGraphicsScene/View
I tried the following:scene = new QGraphicsScene(this); view= new QGraphicsView(this); view->setScene(scene); view->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); view->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); setCentralWidget(view); QBrush q; q.setTextureImage(QImage("resources/list.png")); QGraphicsRectItem* d = new QGraphicsRectItem; d->setRect(30,30,24,24); d->setBrush(q); scene->addItem(d);
But it doesn't look as expected:
The image is not centered in the RectItem and also appears 2x partially...
Also I'm not sure if setTextureImage() is a good way to set an imageIf QGraphicsRectItem is not matter,
simply you can use this way.
MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); QGraphicsScene* scene = new QGraphicsScene(this); QPixmap pixmapItem("/your/image/path/imageNAme.png"); QPixmap pixmapItems = pixmapItem.scaled(QSize(24,24), Qt::KeepAspectRatio); QGraphicsView* view = new QGraphicsView(this); scene->addPixmap(pixmapItems); view->setScene(scene); setCentralWidget(view); }
Edit:
This is very simple and rough solution. there are many better ways also.