[英]I want to create a custom title bar in qt
我想在qt中创建一个自定义标题栏。
因此,我查找了一些示例并进行了跟踪。 这是应用示例的代码。
小部件头文件:
#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);
};
小部件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();
}
}
主窗口标题:
#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);
}
当我运行此代码时,单击并拖动KcWdTitle部分将导致主窗口跟随的位置比我单击的位置更远。
我应该修复代码的哪些部分?
我希望每个人都能听懂我的英语。
您需要更改mousePressEvent()
以减去MainWindow
几何图形而不是标题栏的几何图形。
更改:
m_pCursor = event->globalPos() - geometry().topLeft();
对此:
m_pCursor = event->globalPos() - m_parent->geometry().topLeft();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.