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
Displaying translucent / irregular-shaped windows with Qt
提问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_TranslucentBackground
attribute 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
, mouseMoveEvent
and mouseReleaseEvent
.
如果您希望能够用鼠标移动此窗口,则必须覆盖mousePressEvent
,mouseMoveEvent
和mouseReleaseEvent
。