View Full Version : QBoxLayout with QMainWindow vs QWidget

6th April 2014, 09:49
Hello.I'd like to ask about the thing that is happening ,when I use QHBoxLayout with QMainWindow and with QWidget.I'm trying to change window title style, by connecting 2 widgets.
This what's happening: Under QWidget
Here's the code for class under QWidget:


#include <QMainWindow>
#include <QMouseEvent>
#include <QToolButton>
#include <QStyle>
#include <QLabel>
#include <QHBoxLayout>
#include <QPixmap>

class MyTitleBar : public QWidget
MyTitleBar( QWidget* parent );
public slots:
void showSmall();
void showMaxRestore();

void mousePressEvent( QMouseEvent* me );
void mouseMoveEvent( QMouseEvent* me );

QToolButton* minimize;
QToolButton* maximize;
QToolButton* close;
QToolButton* custom;
QPixmap restorePix, maxPix, closePix, minPix, customPix;
bool maxNormal;
QPoint startPos;
QPoint clickPos;

#endif // MYTITLEBAR_H

#include "mytitlebar.h"

MyTitleBar::MyTitleBar( QWidget* parent )
this->setWindowFlags( Qt::FramelessWindowHint );

minimize = new QToolButton(this);
maximize = new QToolButton(this);
close = new QToolButton(this);
custom = new QToolButton(this);

closePix.load( "close.png" );
close->setIcon( closePix );

maxPix.load( "maximize.png" );
maximize->setIcon( maxPix );

minPix.load( "minimize.png" );
minimize->setIcon( minPix );

customPix.load( "custom_icon.png" );
custom->setIcon( customPix );

QLabel* label = new QLabel(this);
label->setText( "Custom Window" );

QHBoxLayout* HBox = new QHBoxLayout( this );

HBox->addWidget( custom );
HBox->addWidget( label );
HBox->addWidget( minimize );
HBox->addWidget( maximize );
HBox->addWidget( close );


void MyTitleBar::showSmall()


void MyTitleBar::showMaxRestore()


void MyTitleBar::mousePressEvent(QMouseEvent *me)


void MyTitleBar::mouseMoveEvent(QMouseEvent *me)

But under QMainWindow, happens something like this:

The code is exactly the same as for QWidget, but I've changed the parent and inheritance to QMainWindow.And returning to the question why is this happening and how I can fix this? In the main window it's just intancing the class and move it to the right place, that it'd look like a window title bar and is the same as for QWidget and QMainWindow. I need to use QMainWindow as parent, because the main window is inheritance of QMainWindow.

7th April 2014, 10:58
QMainWindow already has a layout.

The content area of a main window is called the central widget, see QMainWindow::setCentralWidget().

So if your code works in a widget, keep it there and set this widget as the central widget or add it to the actual central widget
Or use a QToolBar and add it to the main window.