Qt 实现界面透明

最近喜欢上了Qt,这次小学期C++实训,老师教的是MFC,但我特别不喜欢,成了一名MFC黑。。。

Qt各种方便,而且面向对象体现的更加明显,简洁优雅。

首先继承QDialog,重写paint函数,但是窗口就不能移动了,所以还要重写mouseMoveEvent,要想获得移动时的单击焦点,还要重写mousePressEvent,这样,这个类的头文件是这样的:

#include <QDialog>
#include <QMouseEvent>
#include <QPaintEvent>
#include <QBitmap>

namespace Ui {
class LogInDlg;
}
class LogInDlg : public QDialog
{
    Q_OBJECT
public:
    explicit LogInDlg(QWidget *parent = 0);
    ~LogInDlg();
protected:
    void mouseMoveEvent(QMouseEvent *event);
    void mousePressEvent(QMouseEvent *event);
    void paintEvent(QPaintEvent *event);
private:
    QPoint dragPosition;
    Ui::LogInDlg *ui;
};

cpp文件是这样的:

LogInDlg::LogInDlg(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::LogInDlg)
{
    ui->setupUi(this);
    connect(ui->pushButton_exit, SIGNAL(clicked(bool)), this, SLOT(close()));
    this->setWindowFlags(Qt::FramelessWindowHint);    //隐藏边框
    QPixmap pix;     //加载背景图片
    pix.load(":/images/LogInBackground.png", 0, Qt::AvoidDither|Qt::ThresholdAlphaDither|Qt::ThresholdDither);
    resize(pix.size());
    this->setMask(pix.mask());
}

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

void LogInDlg::mouseMoveEvent(QMouseEvent *event)
{
    if (event->buttons() & Qt::LeftButton)//拦截左键
    {
        move(event->globalPos() - this->dragPosition);//定位窗口新位置
        event->accept();//默认处理过程
    }
}

void LogInDlg::mousePressEvent(QMouseEvent *event)
{
    if (event->button()==Qt::LeftButton)//拦截点击左键动作
    {
        this->dragPosition = event->globalPos() - this->frameGeometry().topLeft(); //计算窗口起始位置并保存
        event->accept();//默认处理过程
    }
}

void LogInDlg::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    painter.drawPixmap(0, 0, QPixmap(":/images/LogInBackground.jpg"));//重绘图片
}

欢迎留言