gpt4 book ai didi

c++ - Qt - 在不使用 WA_TranslucentBackground 的情况下使用图像作为背景渲染 QFrame

转载 作者:行者123 更新时间:2023-11-30 01:12:23 25 4
gpt4 key购买 nike

我需要设置一个带有背景图片的QFrame:http://imgur.com/RnSghvV .这是我尝试过的:

setAutoFillBackground(true);
setWindowFlags(Qt::FramelessWindowHint);
setStyleSheet("background: transparent;");
QPalette p = this->palette();
p.setBrush(QPalette::Base, QPixmap("ipad.png"));
this->setPalette(p);

这是我得到的:

enter image description here

如您所见,边缘有一个烦人的黑框,我想将其移除,然后只查看图像。我该怎么做?

P.S,可以通过使用属性 Qt::WA_TranslucentBackground 使其工作,如 here 所示.然而,在我的例子中,QFrame 将包含其他子部件,其中一些是通过 OpenGL 渲染的 QImages,设置 Qt::WA_TranslucentBackground 渲染这些图像在 Windows 上不可见。所以我正在寻找一种不使用此属性的解决方案。

编辑:

基于 Evgeny 提出的解决方案,我尝试了这个(我使用 325 x 400 作为小部件的尺寸,因为这些是图像的尺寸):

#include <QApplication>
#include <QLabel>
#include <QBitmap>

int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QLabel l;
l.setWindowFlags(Qt::FramelessWindowHint);
QPixmap p(":/img/ipad.png");
l.setPixmap(p);
l.setScaledContents(true);
l.resize(300, 500); //just to test my idea
l.setMask(p.scaled(l.width(),l.height(),Qt::IgnoreAspectRatio,
Qt::SmoothTransformation).mask());
l.show();
return a.exec();
}

有了这个,它看起来像这样:

enter image description here

右侧和底部仍然显示灰色背景。如果我添加 setStyleSheet("background: transparent"),灰色背景变为黑色。

最佳答案

好的,我终于得到了一个使用 setMask 的完整示例。主要问题是您的图像在边框处有额外的空间。这是 OSX 的问题。在 Windows 上,它可以很好地处理原始图像,但对于 Mac,我已经将其剪切了。你可以在这里得到它:http://smages.com/images/pic2016010ata.png

然后我可以在 mac 上使用 QFrame 获得工作示例。

.h 文件中:

#include <QFrame>
#include <QPixmap>

class TestFrame : public QFrame
{
Q_OBJECT
public:
TestFrame(QWidget* p = 0);

protected:
void resizeEvent(QResizeEvent* e) override;

private:
QPixmap _pix;
};

.cpp 文件中:

#include <QBitmap>

TestFrame::TestFrame(QWidget *p) :
QFrame(p, Qt::FramelessWindowHint | Qt::WindowSystemMenuHint),
_pix(":/img/i2.png")
{
QPalette pal = palette();
pal.setBrush(QPalette::Background, QBrush(_pix));
setPalette(pal);
resize(_pix.width(), _pix.height());
}

void TestFrame::resizeEvent(QResizeEvent *e)
{
QFrame::resizeEvent(e);
setMask(_pix.scaled(size()).mask());
}

这是 OS X 上的截图

enter image description here

第二种解决方案是使用 QLabel 而不是 QFrame ,如下所示:

#include <QApplication>
#include <QLabel>
#include <QBitmap>

int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QLabel l;
l.setWindowFlags(Qt::FramelessWindowHint);
QPixmap p(":/img/ipad.png");
l.setPixmap(p);
l.setScaledContents(true);
l.resize(300, 500); //just to test my idea
l.setMask(p.scaled(l.width(),l.height(),Qt::IgnoreAspectRatio,
Qt::SmoothTransformation).mask());
l.show();
return a.exec();
}

关于c++ - Qt - 在不使用 WA_TranslucentBackground 的情况下使用图像作为背景渲染 QFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34372291/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com