我希望在2秒的时间内逐渐降低QPushButton的不透明度,以完成透明度.为此我使用了QPropertyAnimation类并使用按钮的属性"windowOpacity"来实现效果.但这仅适用于独立的QPushButton.当我为按钮指定了父级时,效果消失了.是否有任何方法可以实现儿童按钮的相同效果?
Arn*_*nce 14
该windowOpacity属性仅适用于顶级窗口,因此不幸的是它无法帮助您在子窗口小部件上设置动画透明度.
标准控制有点问题,并且有许多因素有助于它们的最终外观.您可以采取许多方法,但它们都涉及一定数量的编码.没有简单的方法:)
要设置a的透明度QPushButton,您需要为其设置样式表,或更改调色板的某些属性.由于这些选项都不能由a直接使用QPropertyAnimation,因此您可以创建自己的自定义属性并为其设置动画.
下面是一些代码,它为MainWindow被调用者指定了一个自定义属性alpha.alpha值用于设置按钮颜色的alpha部分.有了这个属性,我们就可以使用QPropertyAnimation它来制作动画.结果是一个淡入淡出的按钮.这只处理按钮背景而不是文本,但它应该为您提供一个起点.
MainWindow.h:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QWidget>
#include <QPushButton>
class MainWindow : public QWidget
{
Q_OBJECT
Q_PROPERTY(int alpha READ alpha WRITE setAlpha);
public:
MainWindow();
virtual ~MainWindow();
private:
int m_alpha;
QPushButton * m_button1, *m_button2;
int alpha() const;
void setAlpha(const int a_alpha);
};
#endif /* MAINWINDOW_H */
Run Code Online (Sandbox Code Playgroud)
MainWindow.cpp :( 更新为包含样式表透明度示例)
#include <QPlastiqueStyle>
#include <QPropertyAnimation>
#include "MainWindow.h"
MainWindow::MainWindow() :
m_button1(0),
m_button2(0),
m_alpha(255)
{
resize(200, 200);
QPalette windowPalette(palette());
windowPalette.setBrush(QPalette::Background, QBrush(QColor(200, 0, 0)));
setPalette(windowPalette);
m_button1 = new QPushButton(this);
m_button1->setText("Palette Transparency");
m_button1->setAutoFillBackground(false);
// NOTE: Changing the button background color does not work with XP Styles
// so we need to use a style that allows it.
m_button1->setStyle(new QPlastiqueStyle());
m_button2 = new QPushButton(this);
m_button2->move(0, 50);
m_button2->setText("Stylesheet Transparency");
m_button2->setAutoFillBackground(false);
m_button2->setStyle(new QPlastiqueStyle());
QPropertyAnimation *animation = new QPropertyAnimation(this, "alpha");
animation->setDuration(1000);
animation->setKeyValueAt(0, 255);
animation->setKeyValueAt(0.5, 100);
animation->setKeyValueAt(1, 255);
animation->setLoopCount(-1);
animation->start();
}
MainWindow::~MainWindow()
{
}
int MainWindow::alpha() const
{
return m_alpha;
}
void MainWindow::setAlpha(const int a_alpha)
{
m_alpha = a_alpha;
QPalette buttonPalette(m_button1->palette());
QColor buttonColor(buttonPalette.button().color());
buttonColor.setAlpha(m_alpha);
buttonPalette.setBrush(QPalette::Button, QBrush(buttonColor));
m_button1->setPalette(buttonPalette);
QString stylesheet("background-color: rgba(0,200,0," + QString::number(m_alpha) + ");");
m_button2->setStyleSheet(stylesheet);
}
Run Code Online (Sandbox Code Playgroud)
main.cpp中:
#include <QtGui/QApplication>
#include "MainWindow.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
MainWindow m;
m.show();
return app.exec();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8382 次 |
| 最近记录: |