【问题标题】:Displaying translucent / irregular-shaped windows with Qt用 Qt 显示半透明/不规则形状的窗口
【发布时间】:2010-11-22 22:43:39
【问题描述】:

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

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

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

【问题讨论】:

    标签: windows user-interface qt cross-platform transparency


    【解决方案1】:

    是的,这是可能的。关键是QWidgetQt::WA_TranslucentBackground属性

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

    半透明圆形窗口.h:

    #include <QWidget>
    
    class TranslucentRoundWindow : public QWidget
    {
        public:
            TranslucentRoundWindow(QWidget *parent = 0);
            virtual QSize sizeHint() const;
    
        protected:
            virtual void paintEvent(QPaintEvent *paintEvent);
    };
    

    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());
    }
    

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

    【讨论】:

    • 复制并粘贴在上面,我得到的只是一个黑色正方形,里面有一个红色圆圈。我错过了什么?
    • 你在什么操作系统上试过?这在 Windows 和 OS X 上运行良好。另外,你使用的是什么 Qt 版本?如果我没记错的话,这个答案是用 Qt 4.4 或 4.5 写的。
    • Linux 3.1.0 64 位,Qt 4.6.3。 QT 附带的示例都可以正常工作。
    • 在 Windows 上,您必须在窗口构造函数中有 setWindowFlags(Qt::FramelessWindowHint);
    【解决方案2】:

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

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

    【讨论】:

    • 这并没有解决问题的半透明部分。
    猜你喜欢
    • 2021-04-10
    • 1970-01-01
    • 2015-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-12
    • 1970-01-01
    相关资源
    最近更新 更多