Qt繪制不規則窗體


Qt在做界面(分QWindow 和QWidget兩類)時,不僅僅有windows窗體風格,還有無標題的窗體(實則 去掉了標題欄和側邊滾動條欄).

下面是我通過繼承QWidget基類,做了一個龍圖形的不規則窗體,支持 鼠標左鍵拖動 和 右鍵關閉程序 效果如下:

實際上窗體中只是畫了一個背景透明的圖片 /image/dragon.gif 利用Qt的setMask()函數做出遮罩效果。

主要代碼如下widget.cpp

首先是頭文件:

#include "widget.h"
#include "ui_widget.h"
#include <QPixmap>
#include <QBitmap>
#include <QPainter>
#include <QMouseEvent>

接着是構造函數:

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    QPixmap pix;
    //加載圖片
    pix.load(":/image/dragon.gif");
    //設置窗口大小為圖片大小
    resize(pix.size());
    //窗口設置遮罩
    setMask(pix.mask());
}

Widget::~Widget()
{
    delete ui;
}

畫圖:

void Widget::paintEvent(QPaintEvent *)
{
    QPainter painter(this);
    //從窗口左上角開始繪制圖片
    painter.drawPixmap(0,0,QPixmap(":/image/dragon.gif"));
}

鼠標按下事件:

void Widget::mousePressEvent(QMouseEvent *event)
{
    if(event->button()== Qt::LeftButton)
    {
       // QPoint temp;
        offset=event->globalPos()-pos();
        //move(temp);
    }
    //關閉窗口
    else if(event->button()==Qt::RightButton)
    {
        close();
    }
}

鼠標移動事件:

void Widget::mouseMoveEvent(QMouseEvent *event)
{
    if(event->buttons()&Qt::LeftButton)
    {
        QPoint temp;//移動距離
        //光標形狀
        QCursor cursor;
        cursor.setShape(Qt::OpenHandCursor);
        setCursor(cursor);

        temp=event->globalPos()-offset;
        move(temp);//指針位置和窗口位置的差值
    }
}

鼠標釋放事件:

void Widget::mouseReleaseEvent(QMouseEvent *event)
{
    if(!event->buttons())
    {
        QCursor cursor;
        cursor.setShape(Qt::ArrowCursor);
        setCursor(cursor);
    }
           //QApplication::restoreOverrideCursor();//恢復鼠標指針
}

整個過程就此結束,還是比較簡單的。。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM