2017-04-10 99 views
0

我想在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); 
}; 

的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(); 
    } 
} 

主窗口標題:

#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部將導致主窗口中以進一步跟隨比我點擊的點。

我應該修復哪些代碼部分?

我希望每個人都能理解我的英語。

+0

嘗試改變:'無效KcWdTitlebar :: mousePressEvent(QMouseEvent *事件)'和'無效KcWdTitlebar :: mouseMoveEvent(QMouseEvent *事件) '看看行爲是否有變化。如果是這種情況,那麼它就是你應該改變的部分。 – basslo

+0

Ui :: mainwindow的完整定義在哪裏? –

+0

@DavidGrayson Ui :: mainwindow中沒有太多。我只是將KcWdTitlebar添加到框架的頂部。 – minjee

回答

1

您需要更改mousePressEvent()以減去MainWindow幾何體而不是標題欄的幾何體。

變化:

m_pCursor = event->globalPos() - geometry().topLeft(); 

要這樣:

m_pCursor = event->globalPos() - m_parent->geometry().topLeft(); 
+0

謝謝!這行得通!!!! – minjee

+0

@minjee很高興聽到!你能接受我的回答嗎:) – mrg95