Search code examples
qt4qwidget

How to force QWidget to be shown in a separate window?


I have

class MyWidget : public QWidget
{
    Q_OBJECT
public:
    explicit MyWidget (QWidget *parent);
    // ...
};

// here is ALL the code in MyWidget constructor
MyWidget::MyWidget(QWidget *parent)
    : QWidget(parent)
{
    glWidget = new GLWidget(this, cluster);

    QHBoxLayout *mainLayout = new QHBoxLayout;
    mainLayout->addWidget(glWidget);
    setLayout(mainLayout);

    setWindowTitle("Visualization");
}

and the main window MainWindow w;.

I want

  1. to create new instances of MyWidget from w;
  2. that instances to be destroyed after QCloseEvent or with w (now they are destroyed only after QCloseEvent);
  3. that instances to appear in new windows.

I am creating new instance of MyWidget like this:

void MainWindow::visualize()
{
    MyWidget *widg = new MyWidget(this); // or widg = new MyWidget(0)
    widg->show();
    widg->raise();
    widg->activateWindow();
}

When I try to create widg with w as a parent, widg appears inside of the w (in left top corner).

What is the easiest and most clear way to fix that?

Thanks!


Solution

  • MyWidget::MyWidget(QWidget *parent)
        : QWidget(parent, Qt::Window)
    {
        glWidget = new GLWidget(this, cluster);
    
        QHBoxLayout *mainLayout = new QHBoxLayout;
        mainLayout->addWidget(glWidget);
        setLayout(mainLayout);
    
        setWindowTitle("Visualization");
    }
    

    Adding Qt::Window to the constructor of QWidget should do what you want.