Qt4: Placing QMainWindow instance inside other QWidget/QMainWindow

user666491 picture user666491 · Jun 14, 2011 · Viewed 7.3k times · Source

I'd like to place QMainWindow instance inside another QWidget (for example centralWidget of another QMainWindow).

I'm wondering why it doesn't work ? QMainWindow inherits directly from QWidget. Placeing QWidget inside another QWidget works fine.

I often place QMainWindow instances in QTabBar without any problems.

ps You may ask why do I need to use QMainWindow ? I want to place 2 widgets inside 1 form using vertical layout. I want both widgets to have seperate Toolbars directly over them.

Maybe there is some other way to place toolbars inside plain QWidgets using QtCreator ?


Edit

First example (works fine)

I create new class/form based on QWidget. (QtCreator creates 3 files *.cpp, *.h and *.ui based on standard templates).

Class declaration looks like this

class NotesEditor : public QWidget
{
    Q_OBJECT

public:
    explicit NotesEditor(QWidget *parent = 0);
    ~NotesEditor();

private:
    Ui::NotesEditor *ui;
};

When I try to use this widget and place it inside another widget it works fine. I used "promote to ..." feature of qtcreator - no problems here.

Second example (doesn't work)

I create new class/form based on QMainWindow. (QtCreator creates 3 files *.cpp, *.h and *.ui based on standard templates).

Class declaration looks like this:

class Notes : public QMainWindow
{
    Q_OBJECT

public:
    explicit Notes(QWidget *parent = 0);
    ~Notes();

private:
    Ui::Notes *ui;
};

And now when I try to place this widget in another widget its not visible. Same as before I used "promote to ..." feature of qtcreator.

Both widgets (first based on QWidget, second based on QMainWindow) have the same default structure based on standard qtcreator code templates. I didn't change much here - just added some buttons in the form designer.

In the second example I tried to use setEnabled(true) and setVisible(true) on the class instance. The first one gives no results. The second one opens this widget in seperate window.


I think that the big question is what probibits QMainWindow to be nested inside another QWidget. As I wrote before QMainWindow instances can be placed inside QTabWidgets without any problems.

Answer

Bgie picture Bgie · Aug 8, 2012

Having the same problem, I found the solution here.

QMainWindow sets its window type to Qt::Window so that it will be in an independent window even if it has a parent (you can confirm this by calling show() on your QMainWindow, and you will see it in its own window). Try adding the line

window->setWindowFlags(Qt::Widget);

after you construct the QMainWindow.