c++ - 用 QLinearGradient 绘制 QPushButton

标签 c++ qt

我正在尝试使用 QLinearGradient 来绘制 QPushButton 但没有成功。我找到了如何用纯色绘制它的示例。但是我没有成功找到颜色渐变的例子。而且,我的方法没有奏效。

这是我的完整示例,其中纯色按钮有效而线性渐变按钮无效:

#include <QApplication>
#include <QGridLayout>
#include <QLinearGradient>
#include <QPalette>
#include <QPushButton>

int main(int argc, char** argv)
{
  QApplication app(argc, argv);

  // Create layout
  QGridLayout* layout = new QGridLayout;

  // Create first button
  QPushButton* button_1 = new QPushButton();
  layout->addWidget(button_1, 0, 0);
  QPalette palette_1 = button_1->palette();
  palette_1.setColor(QPalette::Button, Qt::red);
  button_1->setPalette(palette_1);
  button_1->update();

  // Create second button
  QPushButton* button_2 = new QPushButton();
  layout->addWidget(button_2, 0, 1);
  QLinearGradient gradient_button(0, 0, button_2->width(), 0);
  gradient_button.setColorAt(0, Qt::white);
  gradient_button.setColorAt(1, Qt::black);
  QPalette palette_2 = button_2->palette();
  QBrush brush(gradient_button);
  palette_2.setBrush(QPalette::Button, brush);
  button_2->setPalette(palette_2);
  button_2->update();

  // Create widget
  QWidget* widget = new QWidget;
  widget->setLayout(layout);
  widget->resize(300, 50);

  /// Show
  widget->show();

  // Run
  return app.exec();
}

关于我做错了什么有什么想法吗?

最佳答案

没有成功,我用 QPalette 尝试了它,并使用 setStyleSheet 成功地完成了它:

QPushButton* button = new QPushButton();
QString linearGradient = QString("qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 rgba(0, 0, 0, 255), stop:1 rgba(255, 255, 255, 255));");

button->setStyleSheet(QString("background-color: %1").arg(linearGradient));

此外,我们还可以使用QString::arg(...) 为渐变设置不同的颜色和点。

希望这对你有帮助,请原谅我之前的愚蠢评论)

关于c++ - 用 QLinearGradient 绘制 QPushButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54304794/

相关文章:

c# - 获取设备句柄时出错

c++ - 功能: Getting clicked object from QGraphicsScene

qt - 对象::连接:没有这样的信号

c++ - 传递对构造函数的引用,默认参数

c++ - 如何在 MacOS 运行时更改 Qt 应用程序的停靠栏图标?

android - Android 是否支持 Qt QSharedMemory?

c++ - 如何使用 QDataStream::readBytes()

c++ - 使用STL vector 复制构造函数与赋值运算符

c++ - 阻止通过 ifstream 对象从 FIFO 读取

c++ - Qt 的新信号/槽语法出现问题 - 连接到一个简单的函数