一、新建一个widget类的qt程序,然后添加几个按钮,基本布局如下:
二、在加上按钮之后,需要做的是将之前的qt默认的放大缩小、关闭等系列的功能进行屏蔽,在构造函数中
加上如下的代码:
setWindowFlags(Qt::FramelessWindowHint);//这边就是相当于直接将qt窗体默认的功能全部取消
三、开始进行放大、缩小、关闭的设置,可以有两种方式,但实用性较高的是第一种方式:
第一种方式:
在构造函数中加上:
connect(ui->closeButton, SIGNAL(clicked()), this, SLOT(close()));
connect(ui->minButton, SIGNAL(clicked()), this, SLOT(showMinimized()));
connect(ui->maxButton, SIGNAL(clicked()), this, SLOT(showMaximized()));
可以直接实现,以上是第一种较为实用的方式
第二种,本人认为不太实用:开始通过程序默认的ui文件进入,如图:
进入程序里,找到如下的位置:
开始进行信号和槽的绑定工作:
代码如下:
QObject::connect(closeButton, SIGNAL(clicked()), Widget, SLOT(close()));
QObject::connect(minButton, SIGNAL(clicked()), Widget, SLOT(showMinimized()));
QObject::connect(maxButton, SIGNAL(clicked()), Widget, SLOT(showMaximized()));
这个时候可以直接编译,就可以实现放大缩小,但是我们会发现,由于在构造函数中加上了一句
setWindowFlags(Qt::FramelessWindowHint);就是将直接的代码进行了屏蔽,这样做的结果是直接导致窗体无法进行拖动了
所以必须重写鼠标事件:
以下需要重写的鼠标事件是鼠标按下,鼠标释放、鼠标移动
一、先加上头文件
#include <QMouseEvent>
在Widget.h文件中:
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QMouseEvent>
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
private:
Ui::Widget *ui;
bool mousepress;
QPoint point;
protected:
void mouseReleaseEvent(QMouseEvent *event);
void mousePressEvent(QMouseEvent *event);
void mouseMoveEvent(QMouseEvent *event);
};
#endif // WIDGET_H
在widget.cpp文件中:
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
setWindowFlags(Qt::FramelessWindowHint);//这边就是相当于直接将qt窗体默认的功能全部取消
mousepress = false;
connect(ui->closeButton, SIGNAL(clicked()), this, SLOT(close()));
connect(ui->minButton, SIGNAL(clicked()), this, SLOT(showMinimized()));
connect(ui->maxButton, SIGNAL(clicked()), this, SLOT(showMaximized()));
}
Widget::~Widget()
{
delete ui;
}
//鼠标释放
void Widget::mouseReleaseEvent(QMouseEvent *event)
{
Q_UNUSED(event);
mousepress = false;
}
//鼠标按下
void Widget::mousePressEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton)//判断左键是否按下
{
mousepress = true;
point = event->pos();
}
}
//鼠标移动
void Widget::mouseMoveEvent(QMouseEvent *event)
{
if (mousepress)
{
move(event->pos() - point + pos());//移动当前窗口
}
}
在main文件中:
#include "widget.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w;
w.show();
return a.exec();
}
最后实现完成,结果如图所示: