用Qt显示半透明/不规则形状的窗户

Ton*_*ony 12 windows user-interface qt transparency cross-platform

是否可以用Qt显示半透明和/或不规则形状的窗户?

(我假设它最终取决于底层GUI系统的功能,但让我们假设至少Windows XP/Mac OS X)

如果是这样,一个人如何做到这一点?

0xc*_*ced 11

对的,这是可能的.关键是Qt::WA_TranslucentBackground属性QWidget

这是一个简单的类,绘制一个圆形半透明窗口,红色背景为50%alpha.

TranslucentRoundWindow.h:

#include <QWidget>

class TranslucentRoundWindow : public QWidget
{
    public:
        TranslucentRoundWindow(QWidget *parent = 0);
        virtual QSize sizeHint() const;

    protected:
        virtual void paintEvent(QPaintEvent *paintEvent);
};
Run Code Online (Sandbox Code Playgroud)

TranslucentRoundWindow.cpp:

#include <QtGui>

#include "TranslucentRoundWindow.h"

TranslucentRoundWindow::TranslucentRoundWindow(QWidget *parent) : QWidget(parent, Qt::FramelessWindowHint)
{
    setAttribute(Qt::WA_TranslucentBackground);
}

QSize TranslucentRoundWindow::sizeHint() const
{
    return QSize(300, 300);
}

void TranslucentRoundWindow::paintEvent(QPaintEvent *)
{
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);
    painter.setPen(Qt::NoPen);
    painter.setBrush(QColor(255, 0, 0, 127));

    painter.drawEllipse(0, 0, width(), height());
}
Run Code Online (Sandbox Code Playgroud)

如果您希望能够使用鼠标移动此窗口,则必须覆盖mousePressEvent,mouseMoveEventmouseReleaseEvent.