qt 視窗無標題在案頭移動,不可移出可視範圍之外

來源:互聯網
上載者:User

標籤:qt   c++ 視窗移動   

下面是基類的原始碼,把所需求移動的視窗類別繼承這個基類即可

標頭檔:

/************************************************************************//*BaseWidget.h                                                          *//************************************************************************/#ifndef BASEWIDGET_H#define BASEWIDGET_H#include <QWidget>class BaseWidget : public QWidget{Q_OBJECTpublic:BaseWidget(QWidget *parent = 0);~BaseWidget();protected:void mousePressEvent(QMouseEvent *event);void mouseMoveEvent(QMouseEvent *event);void mouseReleaseEvent(QMouseEvent*event);bool m_moving;//用來標記是否滑鼠移動QPoint m_offset;private:};#endif // BASEWIDGET_H

CPP檔案:

/************************************************************************//* BaseWidget.cpp                                                       *//************************************************************************/#include "BaseWidget.h"#include <QMouseEvent>#include <QDesktopWidget>#include <QApplication>BaseWidget::BaseWidget(QWidget *parent): QWidget(parent,Qt::FramelessWindowHint),m_moving(false){}BaseWidget::~BaseWidget(){}void BaseWidget::mousePressEvent( QMouseEvent *event ){if((event->button() == Qt::LeftButton)){m_moving = true;m_offset = event->pos();}}void BaseWidget::mouseMoveEvent( QMouseEvent *event ){if(m_moving){//方法1:QDesktopWidget* desktop = QApplication::desktop();QRect windowRect(desktop->availableGeometry());QRect widgetRect(this->geometry());QPoint point(event->globalPos() - m_offset);//以下是防止視窗拖出可見範圍外//左邊if (point.x() <= 0){point = QPoint(0,point.y());}//右邊int y = windowRect.bottomRight().y() - this->size().height();if (point.y() >= y && widgetRect.topLeft().y() >= y){point = QPoint(point.x(),y);}//上邊if (point.y() <= 0){point = QPoint(point.x(),0);}//下邊int x = windowRect.bottomRight().x() - this->size().width();if (point.x() >= x && widgetRect.topLeft().x() >= x){point = QPoint(x,point.y());}move(point);//方法2://可以通過判斷QRect windowRect是否包含(contains) QRect widgetRect 再移動//這裡沒有給出代碼}//如果只是要求移動視窗,用以下代碼即可實現//move(event->globalPos() - m_offset);}void BaseWidget::mouseReleaseEvent( QMouseEvent*event ){if(event->button() == Qt::LeftButton)m_moving = false;}



qt 視窗無標題在案頭移動,不可移出可視範圍之外

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.