2
votes

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 enter image description here

This is the code for this: TitleBar.h

#ifndef MYTITLEBAR_H
#define MYTITLEBAR_H

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

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

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

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

#endif // MYTITLEBAR_H

TitleBar.cpp

#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)
{

}

Under QMainWindow: enter image description here

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.

1

1 Answers

2
votes

The problem is that QMainWindow already has a layout, see the documentation here, so the code won't work the same way as for a QWidget, you need to use the centralWidget, set a layout to centralWidget and add all your widgets to the layout.