PDA

View Full Version : QGraphicsItem doesn't overlap perfectly a background image



nilot
29th June 2017, 13:59
Hello,

I have a black rectangle whose coordinates are (90,90) , (90,100), (150, 100) and (150, 90) drawn on a white background ( see test_6.png) 12505
I use this image as a background image on my qgraphicsScene.

I want to draw a red QGraphicsRectItem that overlaps perfectly the black rectangle.





#include <QApplication>
#include <QGraphicsScene>
#include <QGraphicsView>
#include <QGraphicsRectItem>
#include <QPen>


int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QGraphicsScene scene;
QGraphicsRectItem* item = new QGraphicsRectItem(QRectF(90,90,60, 10));

QPen pen = QPen(Qt::red, 1, Qt::SolidLine);
pen.setCosmetic(true);
item->setBrush(QColor(255, 0, 0));
item->setPen(pen);
scene.addItem(item);

QPixmap image = QPixmap("path_to_image");
scene.setSceneRect(image.rect());
QGraphicsView view(&scene);
view.setBackgroundBrush(QBrush(image));
view.show();
view.scale(3,3); // in order to see the problem

return a.exec();
}

However I notice a small difference of one pixel at the right and at the bottom of my QGraphicsItem : indeed I shouldn't see any black pixel if the overlap was perfect ( see 12504)

Do you understand why there is such a problem ?

Thank you

Santosh Reddy
29th June 2017, 15:03
Dimensions of the black rectangle in the background is 61x11 (not 60x10). You have to count the pixels covered by the black color, it includes both start pixel and end pixel.

nilot
29th June 2017, 16:15
Ok I understand that, but if I use 61*11 as the dimension of my QGraphicsRectitem when I do item->rect()->topRight(), I get (151, 90) which is the expected value, but it is weird because it doesn't match the top right pixel of my image : (150, 91).

Santosh Reddy
30th June 2017, 06:29
This deviation is because of the basic way how Qt Coordinate system works.

Read http://doc.qt.io/qt-4.8/coordsys.html