Qt 不规则窗体编程

来源:互联网 发布:168开奖网源码 编辑:程序博客网 时间:2024/06/07 03:36
有些时候,为了创建个性化软件界面,往往需要各种形状的窗口,这就有别于传统的窗口了!那么,怎么处理类似的界面呢?我们可以通过继承QWidget、QDialog等类来派生新类,在新类中重新实现基类中的虚函数如:mousePressEvent、mouseMoveEvent、paintEvent。为什么要重新实现这些函数呢?因为不规则窗口不存在边框,如果想要通过鼠标来实现窗口位置变换、相应用户拖拽等动作的话,必须要实现这些过程。同理,重画函数也要重写,用以完成窗体上绘制图片的工作。

    代码实现:

    dialog.h

#ifndef DIALOG_H

#define DIALOG_H
#include <QDialog>
#include <QPoint>
namespace Ui {
    class Dialog;
}
class Dialog : public QDialog
{
    Q_OBJECT
public:
    explicit Dialog(QWidget *parent = 0);
    ~Dialog();
private:
    Ui::Dialog *ui;
    QPoint dragPosition;
protected:
    void mousePressEvent(QMouseEvent *);
    void mouseMoveEvent(QMouseEvent *);
    void paintEvent(QPaintEvent *);
};
#endif // DIALOG_H

    

    dialog.cpp

#include "dialog.h"

#include "ui_dialog.h"
#include <QBitmap>
#include <QPainter>
#include <QMouseEvent>
Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{
    ui->setupUi(this);
    QPixmap pixmap;
    pixmap.load("./images/test.png",0,Qt::AvoidDither|
                Qt::ThresholdAlphaDither|
                Qt::ThresholdDither);//加载图片,并指明避免图片抖动模式
    resize(pixmap.size());//重设窗口大小以图片大小为准
    this->setMask(pixmap.mask());//为图片设定遮罩,被遮罩部分在运行的时候是透明的
}
Dialog::~Dialog()
{
    delete ui;
}
void Dialog::mousePressEvent(QMouseEvent *event)
{
    if (event->button()==Qt::LeftButton)//拦截点击左键动作
    {
        this->dragPosition = event->globalPos()
                             -this->frameGeometry().topLeft();//计算窗口起始位置并保存
        
        event->accept();//默认处理过程
    }
    else if (event->button()==Qt::RightButton)//拦截单击右键动作
    {
        close();         //点击右键关闭程序
    }
}
void Dialog::mouseMoveEvent(QMouseEvent *event)
{
    if (event->buttons() & Qt::LeftButton)//拦截左键
    {
        move(event->globalPos()-this->dragPosition);//定位窗口新位置
        event->accept();//默认处理过程
    }
}
void Dialog::paintEvent(QPaintEvent *)
{
    QPainter painter(this);
    painter.drawPixmap(0,0,QPixmap("./images/test.png"));//重绘图片
}
 
程序运行效果如下:
 
 
    当然,这个程序只绘制了界面,如果施加功能的话,需要在界面上添加各种可视部件,那可视部件
也可以用相似的办法处理的,关键是看你要实现什么样的界面!我的美术没有那么好,所以,估计需要
一位大师级的美工给我设计了。
0 0
原创粉丝点击