Qt渐变染色

Posted 西北逍遥

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Qt渐变染色相关的知识,希望对你有一定的参考价值。

Qt渐变染色

ColorGradientTest1.pro

#-------------------------------------------------
#
# Project created by QtCreator 2021-05-29T19:30:05
#
#-------------------------------------------------

QT       += core gui

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = ColorGradientTest1
TEMPLATE = app

# The following define makes your compiler emit warnings if you use
# any feature of Qt which has been marked as deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS

# You can also make your code fail to compile if you use deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0


SOURCES += \\
        main.cpp \\
        mainwindow.cpp

HEADERS += \\
        mainwindow.h

FORMS += \\
        mainwindow.ui

 

mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QtGui/QPainter>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

    void drawArea1();

protected:
    void paintEvent(QPaintEvent *);

private:
    Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H

 

mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"



MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}



void MainWindow::paintEvent(QPaintEvent *)
{
    QPainter painter(this);
    // 反走样
    painter.setRenderHint(QPainter::Antialiasing, true);

    // 设置渐变色,设置起点、终点
    QLinearGradient linear(100, 100, 200, 100);
    linear.setColorAt(0, QColor(145, 218, 204));
    linear.setColorAt(1, QColor(47, 141, 237));

    // 设置显示模式
    linear.setSpread(QGradient::PadSpread);

    // 设置画笔颜色、宽度
    painter.setPen(QPen(QColor(255, 255, 255, 0), 1));

    // 设置画刷填充
    painter.setBrush(QBrush(linear));

    // 绘制矩形
    painter.drawRect(QRect(100, 100, 200, 100));

}


void MainWindow::drawArea1()
{

}


//////////

 

main.cpp
#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    return a.exec();
}

 

 

参考:https://www.cnblogs.com/ybqjymy/p/13571546.html

https://blog.csdn.net/wzz953200463/article/details/100637732

#################

以上是关于Qt渐变染色的主要内容,如果未能解决你的问题,请参考以下文章

QT 实用代码片段

Qt 绘图渐变填充

Qt 之图形(渐变填充)

Qt 2D绘图 渐变填充(三种渐变方式)

片段着色器不会在 OpenGL GLSL 中创建像光一样的渐变

Qt之渐变及其应用(绘制温度计仪表盘和指示灯)