如何将对象添加到 qt 中的现有布局中? - 解决了

How to add an object into an existing layout in qt? --Solved

我正在做一个 qt 项目,我想将一个对象作为小部件添加到我的布局中,我该怎么做?

int main(int argc, char *argv[])
{

        QApplication app(argc, argv);
        GLobj obj; //this is the object I want to add and it extends QGLWidget
        QWidget *window = new QWidget;
        QGridLayout *grid = new QGridLayout;

        grid->addWidget(&obj,0,0,4,5);//it works

        window->setLayout(grid);            
        window->show();
        return app.exec();
 }

如文档中指定的那样 here

addWidget(*Widget, row, column, rowspan, colspan)

所以替换

grid->addWidget(obj);//I'm not able to do it..

grid->addWidget(obj, 1, 1, 2, 2); //Now I'm able to do it.. :)

QGridLayout::addWidget 方法期望一个指针 指向 QWidget 派生的实例 class,因此如果 GLobj 恰好是某事喜欢:

class GLobj : public QWidget
{
...

你可以做到:

grid->addWidget(&obj);