Qt在作界面(分QWindow 和QWidget兩類)時,不單單有windows窗體風格,還有無標題的窗體(實則 去掉了標題欄和側邊滾動條欄).windows
下面是我經過繼承QWidget基類,作了一個龍圖形的不規則窗體,支持 鼠標左鍵拖動 和 右鍵關閉程序 效果以下:ide
實際上窗體中只是畫了一個背景透明的圖片 /image/dragon.gif 利用Qt的setMask()函數作出遮罩效果。函數
主要代碼以下widget.cppui
首先是頭文件:this
#include "widget.h" #include "ui_widget.h" #include <QPixmap> #include <QBitmap> #include <QPainter> #include <QMouseEvent>
接着是構造函數:spa
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")); }
鼠標按下事件:rest
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(); } }
鼠標移動事件:code
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);//指針位置和窗口位置的差值 } }
鼠標釋放事件:blog
void Widget::mouseReleaseEvent(QMouseEvent *event) { if(!event->buttons()) { QCursor cursor; cursor.setShape(Qt::ArrowCursor); setCursor(cursor); } //QApplication::restoreOverrideCursor();//恢復鼠標指針 }
整個過程就此結束,仍是比較簡單的。。