Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

qt4

qwidget

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!

like image 381
artyom.stv Avatar asked Mar 04 '11 04:03

artyom.stv


2 Answers

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.

like image 185
aukaost Avatar answered Oct 18 '22 01:10

aukaost


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

like image 45
zkunov Avatar answered Oct 17 '22 23:10

zkunov