QGraphicsView 添加QWidget并布局

    QGraphicsScene *scene = new QGraphicsScene;//最好用new的方法,临时变量有时候不起效
    // 创建部件,并关联它们的信号和槽
    QTextEdit *edit = new QTextEdit;
    QPushButton *button = new QPushButton("clear");
    QObject::connect(button, SIGNAL(clicked()), edit, SLOT(clear()));
    // 将部件添加到场景中
    QGraphicsProxyWidget *textEditProxy   = scene->addWidget(edit);
    QGraphicsProxyWidget *pushButtonProxy = scene->addWidget(button);
    // 将部件添加到布局管理器中
    QGraphicsLinearLayout *layout = new QGraphicsLinearLayout;
    layout->addItem((QGraphicsWidget *)textEditProxy);//qt4不需要强转,qt5必须强转
    layout->addItem((QGraphicsWidget *)pushButtonProxy);
    // 创建图形部件,设置其为一个顶层窗口,然后在其上应用布局
    QGraphicsWidget *form = new QGraphicsWidget;
    form->setWindowFlags(Qt::Window);
    form->setWindowTitle("Widget Item");
    form->setLayout(layout);
    scene->addItem(form);
    ui->graphicsView->setScene(scene);

 

你可能感兴趣的:(Qt)