QT制作不规则窗口

195 阅读1分钟

一、给窗口绘图

void Widget::paintEvent(QPaintEvent *event)

{

    QPainter p;

 

    p.begin(this);

 

    p.drawPixmap(0,0,600,600,QPixmap(":/new/picture/1206196.png"));

 

    p.end();

}

 

二、设置窗口属性,隐藏背景

Widget::Widget(QWidget *parent)

    : QWidget(parent)

    , ui(new Ui::Widget)

{

    ui->setupUi(this);

 

    setWindowFlags(Qt::FramelessWindowHint|windowFlags());//去边框,windowFlags()是获取原来的标记

 

    setAttribute(Qt::WA_TranslucentBackground);//隐藏背景

}

 

完成上述步骤后发现无法移动窗口,所以需要重写鼠标移动事件。

 

 

三、重写鼠标点击事件和鼠标移动事件

void Widget::mousePressEvent(QMouseEvent *event)

{

    if(event->button()==Qt::LeftButton)

    {

        pos = event->globalPos() - this->frameGeometry().topLeft();//当前点击的坐标-电脑窗口左上角坐标,这里的pos为QPoint类型的

    }

    else if(event->button()==Qt::RightButton)     //右击关闭窗口

    {

        close();

    }

}

void Widget::mouseMoveEvent(QMouseEvent *event)

{

    if(event->buttons()==Qt::LeftButton)

    {

        move(event->globalPos()-pos);    //移动窗口

    }

}

原理:当点击时,会记住当前点击的位置,和电脑窗口左上角之间的差值。再当移动鼠标时,用当前移动到的坐标位置减去差值,就是要移动的距离。

注意:移动时,button()获取的是没有鼠标,所以用buttons()来获取鼠标的电机状态。