PDA

View Full Version : strange problem in QGraphicsView



Shawn
29th June 2007, 08:51
test::test(QWidget *parent, Qt::WFlags flags)
: QMainWindow(parent, flags)
{
ui.setupUi(this);

QString str = "test";
pixTrans.load("Resources/Trans.bmp");

view.setScene(&scene);
setCentralWidget(&view);

showText(&str,0,0);
showItem(&pixTrans,0,0);
showText(&str,0,100);
showItem(&pixTrans,0,100);
}

void test::showItem(QPixmap *pixmap, int x, int y)
{
QGraphicsPixmapItem* i = scene.addPixmap(*pixmap);
i->setPos(x,y);
}
void test::showText(QString *str, int x, int y)
{
QGraphicsTextItem* i = scene.addText(*str);
i->setPos(x, y);
}
the result is so strange:
the 1st text "test" at (0,0) is covered by the pixmap "pixTrans"
while the 2nd text "test" at (0,0) is on top of the pixmap "pixTrans"
I want to show text on top of pixmap at the same coordinate (x,y), is there any way to do this ?
thanks very much for suggestion!

wysota
29th June 2007, 09:11
I'm not sure what you mean by "at the same coordinate" but you're probably looking for QGraphicsItem::setZValue().

jpn
29th June 2007, 09:18
By the way, QMainWindow::setCentralWidget() takes ownership of the widget and deletes it at the appropriate time so passing a pointer to widget allocated on stack leads to crash by the time the main window is destructed.

Shawn
29th June 2007, 09:24
Thank you very much wysota !
I check the reference for QGraphicsItem::setZValue(), and find out where my problem exist:

"Sibling items that share the same Z-value will be drawn in an undefined order, although the order will stay the same for as long as the items live."
I have tried to find some member function like setTop() or somthing in QGraphicsView with no luck, now I see that the "order" is controled by ZValue, in QGraphicsItem. Thank you very much again!

I set ZValue in showItem() and showText(), and it works well !

void test::showItem(QPixmap *pixmap, int x, int y)
{
QGraphicsPixmapItem* i = scene.addPixmap(*pixmap);
i->setPos(x,y);
i->setZValue(0);
}
void test::showText(QString *str, int x, int y)
{
QGraphicsTextItem* i = scene.addText(*str);
i->setPos(x, y);
i->setZValue(1);
}