Qt自定义窗口(有最大最小化窗口,关闭窗口)

2019-04-15 16:53发布

#include "widget.h"#include #include #include #include Widget::Widget(QWidget *parent) : QWidget(parent){ pic=new QPixmap(); setWindowFlags((Qt::FramelessWindowHint));//设置窗体无边框 setAttribute(Qt::WA_TranslucentBackground);//设置背景透明 pic->load(":/timg.jpg"); resize(pic->size()); int wide = width();//获取界面的宽度 //构建最小化、最大化、关闭按钮 QToolButton *minButton = new QToolButton(this); QToolButton *closeButton= new QToolButton(this); QToolButton *maxButton= new QToolButton(this); //获取最小化、关闭按钮图标 QPixmap minPix = style()->standardPixmap(QStyle::SP_TitleBarMinButton); QPixmap closePix = style()->standardPixmap(QStyle::SP_TitleBarCloseButton); QPixmap maxPix = style()->standardPixmap(QStyle::SP_TitleBarMaxButton); //设置最小化、关闭按钮图标 minButton->setIcon(minPix); closeButton->setIcon(closePix); maxButton->setIcon(maxPix); //设置最小化、关闭按钮在界面的位置 minButton->setGeometry(wide-65,5,20,20); closeButton->setGeometry(wide-25,5,20,20); maxButton->setGeometry(wide-45,5,20,20); //设置鼠标移至按钮上的提示信息 minButton->setToolTip(tr("最小化")); closeButton->setToolTip(tr("关闭")); maxButton->setToolTip(tr("最大化")); //设置最小化、关闭按钮的样式 minButton->setStyleSheet("background-color:transparent;"); closeButton->setStyleSheet("background-color:transparent;"); maxButton->setStyleSheet("background-color:transparent;"); connect(closeButton, SIGNAL(clicked()), this, SLOT(windowclosed())); connect(minButton, SIGNAL(clicked()), this, SLOT(windowmin())); connect(maxButton, SIGNAL(clicked()), this, SLOT(winmax()));}Widget::~Widget(){}void Widget::paintEvent(QPaintEvent *pEvent){ pEvent->ignore(); QPainter painter(this); painter.drawPixmap(0,0,pic->width(),pic->height(),*pic);}void Widget::mousePressEvent(QMouseEvent* mEvent){ if(mEvent->button()==Qt::LeftButton) { dragPosition=mEvent->globalPos()-frameGeometry().topLeft();//globalPos()返回一个全局的位置,pos()返回初始屏幕中光标在全局坐标系中的位置 qDebug()<globalPos();//globalPos()比pos()好用,pos()出了一个框框(初始屏幕)会出现错误 mEvent->accept(); }}void Widget::mouseMoveEvent(QMouseEvent* mEvent){ if(mEvent->buttons()& Qt::LeftButton) { move(mEvent->globalPos()-dragPosition); qDebug()<globalPos(); mEvent->accept(); }}void Widget::windowclosed(){ //QApplication::exit(); this->close();}void Widget::windowmin(){ this->showMinimized();}void Widget::winmax(){ this->showMaximized();}