I want to create a custom title bar in qt.
So I looked up some examples and followed them. Here is the code that applies the example.
Widget header file :
#include <QWidget>
#include <QMouseEvent>
class KcWdTitlebar :public QWidget
{
private:
QWidget *m_parent;
QPoint m_pCursor;
public:
KcWdTitlebar( QWidget *parent) ;
protected:
void mousePressEvent(QMouseEvent *event);
void mouseMoveEvent(QMouseEvent *event);
};
Widget cpp :
KcWdTitlebar::KcWdTitlebar(QWidget *parent ) :m_parent(parent)
{
QLabel *title = new QLabel(parent->windowTitle());
QPushButton *pPB = new QPushButton ("x");
QHBoxLayout *layout = new QHBoxLayout(this);
layout->addWidget(title);
layout->addWidget(pPB);
connect(pPB,SIGNAL(clicked()),parent,SLOT(close()));
}
void KcWdTitlebar::mousePressEvent(QMouseEvent *event)
{
if(event->button() == Qt::LeftButton)
{
m_pCursor = event->globalPos() - geometry().topLeft();
event->accept();
}
}
void KcWdTitlebar::mouseMoveEvent(QMouseEvent *event)
{
if(event->buttons() & Qt::LeftButton)
{
m_parent->move(event->globalPos() - m_pCursor);
event->accept();
}
}
mainwindow header :
#include <QMainWindow>
#include "KcWdTitlebar.h"
namespace Ui {
class mainwindow;
}
class mainwindow : public QMainWindow
{
Q_OBJECT
public:
explicit mainwindow(QWidget *parent = 0);
~mainwindow();
private:
KcWdTitlebar *m_title;
Ui::mainwindow *ui;
};
mainwidow cpp :
mainwindow::mainwindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::mainwindow)
{
ui->setupUi(this);
m_title = new KcWdTitlebar(this);
ui->verticalLayout->addWidget(m_title);
}
When I run this code, Clicking and dragging the KcWdTitle portion will cause the mainwindow to follow further than the point I clicked.
What parts of the code should I fix?
I hope everyone can understand my English.
You need to change mousePressEvent()
to subtract the MainWindow
geometry instead of the title bar's geometry.
Change:
m_pCursor = event->globalPos() - geometry().topLeft();
To this:
m_pCursor = event->globalPos() - m_parent->geometry().topLeft();