背景描述:
在qt下做了一個界面,原標題欄應用時,無法添加左上角圖標,因此自定義了一個標題欄,添加一個qwidget代替。
解決問題:
為了省事,沒有新建title類,直接在mainwindow添加了qwidget,所以處理鼠標事件時,需要對鼠標位置進行額外的判斷處理,只有當前鼠標事件的位置在widget_title的范圍內,才進行事件的處理。
界面描述:
標題欄:widget_title
菜單欄:widget_menu (在widget_title下方)
代碼實現:
重寫mouseDoubleClickEvent、mousePressEvent、mouseMoveEvent三個事件處理函數
頭文件里:
1 // 雙擊標題欄 2 virtual void mouseDoubleClickEvent(QMouseEvent *event); 3 // 點擊標題欄 4 virtual void mousePressEvent(QMouseEvent *event); 5 // 拖動標題欄 6 virtual void mouseMoveEvent(QMouseEvent *event);
cpp里實現
1 void MainWindow::mouseDoubleClickEvent(QMouseEvent *event) 2 { 3 4 int l_titleY = mapToGlobal(ui->widget_title->pos()).y(); 5 int l_menuY = mapToGlobal(ui->widget_menu->pos()).y(); 6 int l_mouseY = event->globalPos().y(); 7 // 判斷鼠標位置 8 if(l_mouseY > l_titleY && l_mouseY < l_menuY) 9 { 10 if(m_bIsMaxWindow)//判斷當前窗口狀態,自己添加實現即可,簡單 11 { 12 showNormal(); 13 } 14 else 15 { 16 showMaximized(); 17 } 18 } 19 } 20 21 void MainWindow::mousePressEvent(QMouseEvent *event) 22 { 23 int l_titleY = mapToGlobal(ui->widget_title->pos()).y(); 24 int l_menuY = mapToGlobal(ui->widget_menu->pos()).y(); 25 int l_mouseY = event->globalPos().y(); 26 if (event->button() == Qt::LeftButton && l_mouseY > l_titleY && l_mouseY < l_menuY) //點擊左邊鼠標 27 { 28 m_dragPosition = event->globalPos() - frameGeometry().topLeft(); 29 //globalPos()獲取根窗口的相對路徑,frameGeometry().topLeft()獲取主窗口左上角的位置 30 event->accept(); //鼠標事件被系統接收 31 } 32 33 } 34 35 void MainWindow::mouseMoveEvent(QMouseEvent *event) 36 { 37 int l_titleY = mapToGlobal(ui->widget_title->pos()).y(); 38 int l_menuY = mapToGlobal(ui->widget_menu->pos()).y(); 39 int l_mouseY = event->globalPos().y(); 40 if (event->buttons() == Qt::LeftButton && l_mouseY > l_titleY && l_mouseY < l_menuY) //當滿足鼠標左鍵被點擊時。 41 { 42 move(event->globalPos() - m_dragPosition);//移動窗口 43 event->accept(); 44 } 45 }