5

我想让背景QDialog透明,这样我就可以透过窗户看到。我问是因为我想使用一个半透明的背景图像来创建一个“圆角窗口”的错觉。使用setOpacity对我来说不是一个选项,因为我希望所有小部件都保持完全不透明。

有没有办法在不使用本机操作系统 API 的情况下实现这一目标?

4

1 回答 1

12

使用QWidget::setAttribute(Qt::WA_TranslucentBackground);. 请注意,这也需要Qt::FramelessWindowHint设置。

这个例子对我有用:

#include <QtGui>

class Dialog : public QDialog
{
public:
    Dialog() : QDialog(0, Qt::FramelessWindowHint) // hint is required on Windows
    {
        QPushButton *button = new QPushButton("Some Button", this);    
        setAttribute(Qt::WA_TranslucentBackground);
    }

};

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Dialog d;
    d.show();
    return a.exec();
}

关于圆角,QWidget::setMask()会帮助你。

编辑:针对下面评论中的另一个问题,这是一个使用资源文件中的图像的工作示例,它覆盖QWidget::paintEvent()

#include <QtGui>

class Dialog : public QDialog
{
public:
    Dialog() : QDialog(0, Qt::FramelessWindowHint) // hint is required on Windows
    {
        setFixedSize(500, 500); // size of the background image
        QPushButton *button = new QPushButton("Some Button", this);
        setAttribute(Qt::WA_TranslucentBackground);
    }

protected:
    void paintEvent(QPaintEvent *event)
    {
        QPainter painter(this);
        painter.drawImage(QRectF(0, 0, 500, 500), QImage(":/resources/image.png"));
    }
};

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Dialog d;
    d.show();
    return a.exec();
}
于 2012-05-04T15:54:49.737 回答