我想在qt中创建一个自定义标题栏。
所以我查了几个例子,然后跟着它们走。下面是应用该示例的代码。
Widget头文件:
#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 :
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;
};主寡妇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部分将导致主窗口比我单击的点更远。
我应该修复代码的哪些部分?
我希望每个人都能听懂我的英语。
发布于 2017-04-11 16:45:34
您需要更改mousePressEvent()以减去MainWindow几何,而不是标题栏的几何图形。
更改:
m_pCursor = event->globalPos() - geometry().topLeft();对此:
m_pCursor = event->globalPos() - m_parent->geometry().topLeft();https://stackoverflow.com/questions/43319368
复制相似问题