# 【Qt編程】基于Qt的詞典開發系列--無邊框窗口的拖動
在上一篇文章中,我們講述了如何進行無邊框窗口的縮放與拖動,**而在一些情況下,我們的窗口只需要進行拖動也不需要改變其大小**,比如:QQ的登錄窗口。本來在上一篇文章中已經講述了如何進行窗口的拖動,但是卻與窗口的縮放相關的程序放在一起,**下面專門單獨分離出來。**
窗口的拖放只涉及到鼠標事件:按下操作、釋放操作和移動操作,因此只需要重寫這三個函數。由于程序比較簡單,并且注釋也比較詳細,就不作過多介紹。新建一個基類為QWidget的Qt Gui應用程序,**只需修改widget.h和widget.cpp文件如下**:
**1、widget.h文件**
~~~
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>//注意我使用的是Qt5,Qt4與Qt5的區別可以參考http://qt-project.org/wiki/Transition_from_Qt_4.x_to_Qt5
#include<QMouseEvent>
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
QPoint move_point; //移動的距離
bool mouse_press; //鼠標按下
//鼠標按下事件
void mousePressEvent(QMouseEvent *event);
//鼠標釋放事件
void mouseReleaseEvent(QMouseEvent *event);
//鼠標移動事件
void mouseMoveEvent(QMouseEvent *event);
private:
Ui::Widget *ui;
};
#endif // WIDGET_H
~~~
**2、widget.cpp文件**
~~~
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
this->setMouseTracking(false);
setWindowFlags(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint);//設置主窗口無邊框
}
Widget::~Widget()
{
delete ui;
}
void Widget::mousePressEvent(QMouseEvent *event)
{
if(event->button() == Qt::LeftButton)
{
this->setMouseTracking(true);
mouse_press = true;
//鼠標相對于窗體的位置(或者使用event->globalPos() - this->pos())
move_point = event->pos();;
}
}
void Widget::mouseReleaseEvent(QMouseEvent *event)
{
//設置鼠標為未被按下
mouse_press = false;
}
void Widget::mouseMoveEvent(QMouseEvent *event)
{
//若鼠標左鍵被按下
// qDebug()<<"mouse_press="<<event->globalPos();
if(mouse_press)
{
//鼠標相對于屏幕的位置
QPoint move_pos = event->globalPos();
//移動主窗體位置
this->move(move_pos - move_point);
}
}
~~~
- 前言
- <一>--詞典框架設計及成品展示
- <二>--本地詞典的設計
- <三>--開始菜單的設計
- <四>--無邊框窗口的縮放與拖動
- <五>--無邊框窗口的拖動
- <六>--界面美化設計
- <七>--調用網絡API
- <八>--用戶登錄及API調用的實現
- <九>--JSON數據解析
- <十>--國際音標的顯示
- <十一>系統托盤的顯示
- <十二>調用講述人
- <十三>音頻播放
- <十四>自動補全功能
- <十五>html特殊字符及正則表達式
- 后序