代码之家  ›  专栏  ›  技术社区  ›  plank

Qt:QGraphicsAnchorLayout在QScrollArea中不工作

  •  -1
  • plank  · 技术社区  · 2 年前

    我正在尝试在QScrollArea中添加布局

    我最初尝试使用QGraphicsAnchorLayout,但多亏了musicamante的评论,我明白这是不可能的,所以后来我使用了QVBoxLayout,这不起作用,因为我的代码 scene->addWidget(scrollAreaWidget); 行,在删除它之后,我现在有一个在滚动区域中正确显示布局的示例。

    然而,我仍然有一个问题:我的代码现在在运行时抛出这个错误 QGraphicsProxyWidget::setWidget: cannot embed widget 0x... which is not a toplevel widget, and is not a child of an embedded widget 事实证明,我仍然不完全理解代理/嵌入式小部件机制。

    你能帮我找出解决这个错误的方法吗( 场景->addWidget(scrollAreaWidget); 将删除错误,但正如musicamante所解释的那样,会破坏一切)。

    这是我的cpp:

    #include "mainwindow.h"
    #include "qpushbutton.h"
    
    MainWindow::MainWindow(QWidget *parent)
    {
    //Scene setup
        setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
        setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
        scene = new QGraphicsScene();
        setScene(scene);
    //Layout construct    
        scrollAreaLayout = new QVBoxLayout;
    //scroll area construct
        scrollArea = new QScrollArea();
        scrollArea->setHorizontalScrollBarPolicy (Qt::ScrollBarAlwaysOff);
        scrollArea->setVerticalScrollBarPolicy (Qt::ScrollBarAlwaysOn);
        scene->addWidget(scrollArea);
    //parent widget to hold children buttons
        scrollAreaWidget = new QWidget();
        //scene->addWidget(scrollAreaWidget);
        scrollAreaWidget->setLayout(scrollAreaLayout);
    //layout content
        scrollAreaLayout->setSizeConstraint(QLayout::SetFixedSize);
        for(int i = 0; i < 21; ++i){
            QPushButton* but = new QPushButton("testBut", scrollAreaWidget);
            scene->addWidget(but);
            scrollAreaLayout->addWidget(but);
        }
    //set srollArea widget
        scrollArea->setWidget(scrollAreaWidget);
    //set geometry
        resizeEvent(NULL);
    }
    
    void MainWindow::resizeEvent(QResizeEvent *event){
        scene->setSceneRect(0,0,this->width(),this->height());
        scrollAreaLayout->setGeometry(QRect(QPoint(scene->width()-300,100),QSize(300, scene->height() - 100)));
        scrollArea->setGeometry(QRect(QPoint(scene->width()-300,100),QSize(300, scene->height() - 100)));
        scrollAreaWidget->setGeometry(QRect(QPoint(scene->width()-300,100),QSize(300, scene->height() - 100)));
    }
    
    0 回复  |  直到 2 年前