【问题标题】:The transparent button showing an image显示图像的透明按钮
【发布时间】:2016-02-04 20:45:07
【问题描述】:

我想创建一个按钮来显示具有透明背景的给定图像。我正在使用下面的代码段:

ui->setupUi(this);
this->setFixedSize(width, height);

QPixmap* orgPixmap = new QPixmap(":/images/a.png");
QSize size(this->width(), this->height());
QPixmap resizePixmap(orgPixmap->scaled(size));

QPalette palette;
palette.setBrush(this->backgroundRole(), QBrush(resizePixmap));
this->setPalette(palette);

ui->toolButton->setStyleSheet("background-color: rgba(255, 255, 255, 0);");
ui->toolButton->setFixedSize(64, 64);
ui->toolButton->setIconSize(QSize(64, 64));
ui->toolButton->setIcon( QIcon(":/images/add.png") );

在小部件的顶部,我添加了一个带有图标的按钮。这是一个带有透明背景的蓝色圆圈。但是,当我在 Android 设备上部署和运行我的代码时,按钮显示为带有白色的不透明背景。

请看图:

我尝试使用以下代码强制按钮透明:

QColor transparent_color(0,0,0,0);
QPalette button_palette(ui->pushButton->palette());

button_palette.setColor(QPalette::Button, transparent_color);
ui->toolButton->setPalette(button_palette);

上面的代码似乎没有达到我预期的效果。 我想知道问题可能是什么以及如何解决。

【问题讨论】:

  • 你的解释不是很清楚。您希望透明小部件位于另一个小部件之上并且只显示图像?
  • 对不起,我的英语水平不好。但你说的是我想要的东西
  • 你检查过按钮上的setAttribute(Qt::WA_TranslucentBackground, true);吗?
  • 也看看这个问题:stackoverflow.com/questions/2673983/…
  • 我试过“ui->toolButton->setAttribute(Qt::WA_TranslucentBackground, true);”但它仍然无法按我的意愿工作

标签: android c++ qt


【解决方案1】:

我知道你需要一个圆形按钮,那么QWidget::setMask() 怎么样?

QPainterPath path;
path.addEllipse(ui->pushButton->rect());
QRegion mask = QRegion(path.toFillPolygon().toPolygon());
ui->pushButton->setMask(mask);

只是一个想法,我没有测试过。

【讨论】:

    【解决方案2】:

    您可以设置一个简单的样式表。像这样:widget->setStyleSheet(rgba(255, 255, 255,0);"); 如果要调整不透明度,只需更改第四个参数即可。

    【讨论】:

      【解决方案3】:

      我最近在一个基于 Qt Graphics View Framework 的 Win/Mac 项目上解决了类似的问题,请注意我从未在 Android 平台上测试过。

      无论如何,首先您需要为您的图形场景设置 setForegroundBrush():

      ui.yourGraphicsView->scene()->setsetForegroundBrush(Qt::transparent);
      

      您也可以使用 Qt Designer 来获得类似的结果或编辑您的 Project.ui 文件,如下所示:

      <widget class="QGraphicsView" name="yourGraphicsView">
      ...
       <property name="foregroundBrush">
        <brush brushstyle="NoBrush">
         <color alpha="255">
          <red>0</red>
          <green>0</green>
          <blue>0</blue>
         </color>
        </brush>
       </property>
      

      现在 setBackgroundBrush() 对你的按钮来说是透明的:

      ui->toolButton->setBackgroundBrush(Qt::transparent);
      

      我发现这两个足以让透明按钮悬停在 QGraphicScene 中的其他对象上;不需要调用setMask(),因为当 QGraphicsPixmapItem(或祖先)设置为 alpha 通道 PNG 时,Qt 会自动为它执行此操作。对于按钮,它也可以按预期工作:单击 PNG 的透明区域(上面显示为白色)不会触发 OnClick() 事件,而单击基于 PNG 的按钮上的透明部分会。

      希望这会有所帮助...

      【讨论】:

        猜你喜欢
        • 2020-06-11
        • 1970-01-01
        • 2018-12-23
        • 2019-09-21
        • 2010-10-02
        • 2017-11-04
        • 2021-09-18
        • 2020-05-20
        • 2010-10-13
        相关资源
        最近更新 更多