Important: Please read the Qt Code of Conduct -

[SOLVED]How to make QGraphicsItem (QGraphicsProxyWidget in this case) to be visible only inside the boundaries of its parent QWidget? Simple example.

  • 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:
    <code>ui->myLabel->move(-10, 0);</code>
    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:
    <code>QGraphicsProxyWidget *myLabelProxy = this->createProxyForChildWidget(ui->myLabel);
    myLabeProxy->setPos(-10, 0);</code>
    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... Any help is welcome.

  • To make the things easier to understand, I created a simple program (runs only in main) where you guys can undestand my issue:

    #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();

  • You could subclass, reimplement the paint() event, inside of it check the position of the object and skip drawing if it is outside, call the base class paint method if it is on the inside to draw the original object. Might not work but the one sure way to know is to try.

  • Thanks utcenter. But I just found the way. I must set a flag. Example: @myParentProxy->setFlag(QGraphicsItem::ItemClipsChildrentoShape);@

  • If the default clip behavior is the one you want then great.

Log in to reply