windows 使用 Qt 显示半透明/不规则形状的窗口

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1333610/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 13:02:32  来源:igfitidea点击:

Displaying translucent / irregular-shaped windows with Qt

windowsuser-interfaceqtcross-platformtransparency

提问by Tony the Pony

Is it possible to display translucent and/or irregular-shaped windows with Qt?

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

(I'm assuming it ultimately depends on the capabilities of the underlying GUI system, but let's assume at least Windows XP / Mac OS X)

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

If so, how does one accomplish this?

如果是这样,如何实现这一目标?

采纳答案by 0xced

Yes, it is possible. The key is the Qt::WA_TranslucentBackgroundattribute of QWidget

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

Here is a simple class that draws a round translucent window with a red background 50% alpha.

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

TranslucentRoundWindow.h:

半透明圆形窗口.h:

#include <QWidget>

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

    protected:
        virtual void paintEvent(QPaintEvent *paintEvent);
};

TranslucentRoundWindow.cpp:

半透明圆形窗口.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());
}

If you want to be able to move this window with the mouse, you will have to override mousePressEvent, mouseMoveEventand mouseReleaseEvent.

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

回答by Thomi

It certainly is possible. Qt ships with the "Shaped Clock" demonstration. The documentation of which is here.

这当然是可能的。Qt 附带了“Shaped Clock”演示。其文档是here

It creates a top-level window with an odd shape. Should be all you need.

它创建了一个形状奇特的顶级窗口。应该是你所需要的。