View Full Version : QGraphicsItem to be visible only inside the boundaries of its parent. Simple Example

21st January 2013, 04:51
I have a QWidget (myWidget) which contains only a QLabel (myLabel) inside of it. There is no layout around myLabel (myLabel must to be free because I want move it anywhere inside myWidget). So, I put myWidget inside a QGraphicsView (trought a QGraphicsScene). Then I set the position of myLabel this way:
ui->myLabel->move(-10, 0);
The result is that only the final part of myLabel is visible (the initial 10 pixels are not shown on the screen because they are out the myWidget). That’s exactly what I was expecting. But since I’m working with QGraphicsView, I should use QGraphicsProxyWidget (which is a QGraphicsItem) to manipulate the position and to make animation on my widgets. So, what I did:
QGraphicsProxyWidget *myLabelProxy = this->createProxyForChildWidget(ui->myLabel);
myLabeProxy->setPos(-10, 0);
The result is that myLabel is entire visible now. Even the initial 10 pixels which should be hidden because they are outside myWidget. I want that only the parts that are inside the parents widgets boundaries to be visible. Remeber that I wanna use QGraphicsProxyWidget to manipulating the position and to make animations on my widgets to avoid undesirable side effects…
I want to happen the same behavior of the first situation.

A simple example (run this way and later comment the indicated line and uncommented the other 2 lines):

#include <QtGui>
int main(int argc, char *argv[])
QApplication a(argc, argv);
QWidget *w = new QWidget();
QHBoxLayout *layout = new QHBoxLayout();
QGraphicsView *view = new QGraphicsView(w);
QGraphicsScene *scene = new QGraphicsScene();
QWidget *myWidget = new QWidget();
myWidget->setGeometry(0, 0, 200, 100);
QLabel *myLabel = new QLabel(“Text of the Label!!!”, myWidget);
//run with this line commented later
myLabel->move(-10, 0);
//uncomment these 2 lines later
// QGraphicsProxyWidget *myLabelProxy = myWidget->graphicsProxyWidget()->createProxyForChildWidget(myLabel);
// myLabelProxy->setPos(-10, 0);
return a.exec();