9

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!

artyom.stv
  • 2,097
  • 1
  • 24
  • 42

2 Answers2

13
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.

Tarod
  • 6,732
  • 5
  • 44
  • 50
aukaost
  • 3,778
  • 1
  • 24
  • 26
2

As it is written in QWidget's constructor reference for a widget to become a window its parent should be 0. But when the parent is 0 it mens the parent is "YOU" :) - i.e you have to look after them - keep them to some reachable place and destroy them when the time is appropriate (either on close event, destructor or using shared pointers).

zkunov
  • 3,362
  • 1
  • 20
  • 17