第二章 Qt窗体应用------移动无边框窗体

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xuan_xuan_2/article/details/80465965

1、 实例需求
移动无边框窗体。
2、 实例实现
第一步:打开mainwindow.h头文件,添加代码。
<1> 添加头文件:

#include <QMouseEvent>  //引用鼠标类头文件
#include <QPushButton>  //引用按钮类头文件

<2> 添加变量和声明:

//定义鼠标三种状态方法
protected:
    //鼠标按下
    void mousePressEvent (QMouseEvent *e);
    //鼠标移动
    void mouseMoveEvent (QMouseEvent *e);
    //鼠标释放
    void mouseReleaseEvent (QMouseEvent *e);
    //定义QPoint对象
private:
    QPushButton *btClose;
    QPoint last;

第二步:打开mainwindow.cpp源代码文件,添加代码。
<1> 在MainWindow的构造函数中添加如下代码:

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    //标题名
    this->setWindowTitle("移动无边框窗体");
    //去掉标题栏
    this->setWindowFlags(Qt::FramelessWindowHint);
    //实例一个按钮控件,因为去掉标题栏后,窗体没有关闭按钮了。
    //所以自己添加一个按钮实现关闭功能。
    btClose = new QPushButton(this); btClose->setText("关闭");
    //按钮点击事件
    connect(btClose,SIGNAL(clicked()),this,SLOT(close()));

}

<2> 实现函数:

//获取鼠标点定位窗体位置
void MainWindow::mousePressEvent(QMouseEvent *e)
{
    last = e->globalPos();
}
void MainWindow::mouseMoveEvent(QMouseEvent *e)
{
    int dx = e->globalX() - last.x();
    int dy = e->globalY() - last.y();
    last = e->globalPos();
    move(x()+dx,y()+dy);
}
void MainWindow::mouseReleaseEvent(QMouseEvent *e)
{
    int dx = e->globalX() - last.x();
    int dy = e->globalY() - last.y();
    move(x()+dx, y()+dy);
}

3、 效果图
这里写图片描述
今天讲解到现在结束了,想进行视频学习的小伙伴,可以进入我的视频教程进行学习,课程地址:https://edu.csdn.net/course/detail/7275,课程资源下载地址:https://download.csdn.net/download/xuan_xuan_2/10641564,欢迎大家前来学习交流。
这里写图片描述

猜你喜欢

转载自blog.csdn.net/xuan_xuan_2/article/details/80465965
今日推荐