Qt中QPainter的使用

Posted 图灵,图灵,图个机灵

tags:

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

Qt中QPainter的使用

GUI用户界面的优点是通过提供可视化的工具为客户提供便利的操作,界面上的按钮、编辑框等都是通过绘图得到的。Qt的二维绘图基本功能是使用QPainter在绘图设备上绘图,通过绘制基本的点、线、圆等基本图形来组成自己需要的图形,得到的图形是不可以交互操作的。整个绘图系统基于QPainter、QPaintDevice和QPaintEngine三个类。QPainter用来执行绘制操作,QPaintDevice是一个抽象的二维空间,这个抽象的二维空间允许QPainter在上面进行绘制,也就是QPainter的工作空间。QPaintEngine为QPainter提供了在不同设备上进行绘制的接口。绘图设备包括QWidget、QPixmap、QImage等,这些设备的作用为QPainter提供一个“画布”。

QWidget类及其子类是最常用的绘图设备,从QWidget类继承的类都有paintEvent()事件,要在设备上绘图,只需要重写此方法就可以了,

在paintEvent() 事件里的基本代码结构为:

void Widget::paintEvent(QPaintEvent *ev)

    //构造画家对象
    QPainter painter(this);
    //保存当前画家状态
    painter.save();
    ....
    //恢复上面保存的状态
    painter.restore();

常用方法有:

drawLine(绘制线段)

drawRect(绘制矩形)
drawRects(绘制多矩形)
drawEllipse(绘制椭圆)
drawArc(绘制弧)
drawChord(绘制弦)
drawPie(绘制扇形)
drawRoundedRect(绘制带倒角矩形)
drawPoint(绘制点)
drawPoints(绘制多个点)
drawConvexPloygon(绘制凸多边形)
drawPolyline(绘制多段线)
drawPolygon(绘制多边形)
drawText(绘制文本)

代码示例:

画弧线

void Widget::paintEvent(QPaintEvent *ev)

    //构造画家对象
    QPainter painter(this);
    //保存当前画家状态
    painter.save();
    //设置画笔颜色
    painter.setPen(QPen(QColor(Qt::green)));
    //设置抗锯齿
    painter.setRenderHint(QPainter::Antialiasing,true);
    //起始角度
    int startAngle=30*16;
    //跨越角度
    int spanAngle=120*16;
    //绘制弧线
    painter.drawArc(QRectF(30.0,50.0,80.0,70.0),startAngle,spanAngle);
    //恢复上面保存的状态
    painter.restore();

画多边形

void Widget::paintEvent(QPaintEvent *ev)

    //构造画家对象
    QPainter painter(this);
    //保存当前画家状态
    painter.save();
    //设置画笔颜色
    painter.setPen(QPen(QColor(Qt::green)));
    //设置抗锯齿
    painter.setRenderHint(QPainter::Antialiasing,true);
    //多边形的顶点坐标
    static const QPoint pts[4]=
        QPoint(50,50),QPoint(120,50),QPoint(180,200),
        QPoint(50,200)
    ;
    //绘制多边形
    painter.drawPolygon(pts,4);
    //恢复上面保存的状态
    painter.restore();

该文章会更新,欢迎大家批评指正。

推荐一个零声学院免费公开课程,个人觉得老师讲得不错,
分享给大家:[Linux,nginx,ZeroMQ,mysql,Redis,
fastdfs,MongoDB,ZK,流媒体,CDN,P2P,K8S,Docker,
TCP/IP,协程,DPDK等技术内容,点击立即学习:
服务器课程:C++服务器

QT源码拾贝0-5(qimage和qpainter)

目录

0   qt源码查看方法

1.  qimage.cpp中线程池使用方法

2.  qpainter_p.h中SmallStack模板元结构体存放智能指针

3.  qpainter.cpp的保存函数,状态对象赋值使用std::exchange函数

4.  qpainter.cpp中获得类对象的方法

5.  qpainter.cpp中QChar字节操作,使用u在字节前面



0   qt源码查看方法

使用vscode工具,加载qt源码路径,比如:C:\\Qt\\6.5.0\\Src

再按住ctrl+鼠标,可以方便查看引用函数的定义。

返回上次光标位置,使用快捷键Alt和方向左/右键

跳过单个变量,使用快捷键ctrl加方向左/右键

1.  qimage.cpp中线程池使用方法


/*!
    \\since 5.14

    Applies the color transformation \\a transform to all pixels in the image.
*/
void QImage::applyColorTransform(const QColorTransform &transform)

    if (transform.isIdentity())
        return;
    detach();
    if (!d)
        return;
    if (pixelFormat().colorModel() == QPixelFormat::Indexed) 
        for (int i = 0; i < d->colortable.size(); ++i)
            d->colortable[i] = transform.map(d->colortable[i]);
        return;
    
    QImage::Format oldFormat = format();
    if (qt_fpColorPrecision(oldFormat)) 
        if (oldFormat != QImage::Format_RGBX32FPx4 && oldFormat != QImage::Format_RGBA32FPx4
                && oldFormat != QImage::Format_RGBA32FPx4_Premultiplied)
            convertTo(QImage::Format_RGBA32FPx4);
     else if (depth() > 32) 
        if (oldFormat != QImage::Format_RGBX64 && oldFormat != QImage::Format_RGBA64
                && oldFormat != QImage::Format_RGBA64_Premultiplied)
            convertTo(QImage::Format_RGBA64);
     else if (oldFormat != QImage::Format_ARGB32 && oldFormat != QImage::Format_RGB32
                && oldFormat != QImage::Format_ARGB32_Premultiplied) 
        if (hasAlphaChannel())
            convertTo(QImage::Format_ARGB32);
        else
            convertTo(QImage::Format_RGB32);
    

    QColorTransformPrivate::TransformFlags flags = QColorTransformPrivate::Unpremultiplied;
    switch (format()) 
    case Format_ARGB32_Premultiplied:
    case Format_RGBA64_Premultiplied:
    case Format_RGBA32FPx4_Premultiplied:
        flags = QColorTransformPrivate::Premultiplied;
        break;
    case Format_RGB32:
    case Format_RGBX64:
    case Format_RGBX32FPx4:
        flags = QColorTransformPrivate::InputOpaque;
        break;
    case Format_ARGB32:
    case Format_RGBA64:
    case Format_RGBA32FPx4:
        break;
    default:
        Q_UNREACHABLE();
    

    std::function<void(int,int)> transformSegment;

    if (qt_fpColorPrecision(format())) 
        transformSegment = [&](int yStart, int yEnd) 
            for (int y = yStart; y < yEnd; ++y) 
                QRgbaFloat32 *scanline = reinterpret_cast<QRgbaFloat32 *>(d->data + y * d->bytes_per_line);
                QColorTransformPrivate::get(transform)->apply(scanline, scanline, width(), flags);
            
        ;
     else  if (depth() > 32) 
        transformSegment = [&](int yStart, int yEnd) 
            for (int y = yStart; y < yEnd; ++y) 
                QRgba64 *scanline = reinterpret_cast<QRgba64 *>(d->data + y * d->bytes_per_line);
                QColorTransformPrivate::get(transform)->apply(scanline, scanline, width(), flags);
            
        ;
     else 
        transformSegment = [&](int yStart, int yEnd) 
            for (int y = yStart; y < yEnd; ++y) 
                QRgb *scanline = reinterpret_cast<QRgb *>(d->data + y * d->bytes_per_line);
                QColorTransformPrivate::get(transform)->apply(scanline, scanline, width(), flags);
            
        ;
    

#if QT_CONFIG(thread) && !defined(Q_OS_WASM)
    int segments = (qsizetype(width()) * height()) >> 16;
    segments = std::min(segments, height());
    QThreadPool *threadPool = QThreadPool::globalInstance();
    if (segments > 1 && threadPool && !threadPool->contains(QThread::currentThread())) 
        QSemaphore semaphore;
        int y = 0;
        for (int i = 0; i < segments; ++i) 
            int yn = (height() - y) / (segments - i);
            threadPool->start([&, y, yn]() 
                transformSegment(y, y + yn);
                semaphore.release(1);
            );
            y += yn;
        
        semaphore.acquire(segments);
     else
#endif
        transformSegment(0, height());

    if (oldFormat != format())
        *this = std::move(*this).convertToFormat(oldFormat);

2.  qpainter_p.h中SmallStack模板元结构体存放智能指针


    std::unique_ptr<QPainterState> state;
    template <typename T, std::size_t N = 8>
    struct SmallStack : std::stack<T, QVarLengthArray<T, N>> 
        void clear()  this->c.clear(); 
    ;
    SmallStack<std::unique_ptr<QPainterState>> savedStates;

    mutable std::unique_ptr<QPainterDummyState> dummyState;

3.  qpainter.cpp的保存函数,状态对象赋值使用std::exchange函数

void QPainter::save()

#ifdef QT_DEBUG_DRAW
    if (qt_show_painter_debug_output)
        printf("QPainter::save()\\n");
#endif
    Q_D(QPainter);
    if (!d->engine) 
        qWarning("QPainter::save: Painter not active");
        return;
    

    std::unique_ptr<QPainterState> prev;
    if (d->extended) 
        // separate the creation of a new state from the update of d->state, since some
        // engines access d->state directly (not via createState()'s argument)
        std::unique_ptr<QPainterState> next(d->extended->createState(d->state.get()));
        prev = std::exchange(d->state, std::move(next));
        d->extended->setState(d->state.get());
     else 
        d->updateState(d->state);
        prev = std::exchange(d->state, std::make_unique<QPainterState>(d->state.get()));
        d->engine->state = d->state.get();
    
    d->savedStates.push(std::move(prev));

4.  qpainter.cpp中获得类对象的方法


QBrush QPaintEngineState::brush() const

    return static_cast<const QPainterState *>(this)->brush;

5.  qpainter.cpp中QChar字节操作,使用u在字节前面

int old_offset = offset;
    for (; offset < text.size(); offset++) 
        QChar chr = text.at(offset);
        if (chr == u'\\r' || (singleline && chr == u'\\n')) 
            text[offset] = u' ';
         else if (chr == u'\\n') 
            text[offset] = QChar::LineSeparator;
         else if (chr == u'&') 
            ++maxUnderlines;
         else if (chr == u'\\t') 
            if (!expandtabs) 
                text[offset] = u' ';
             else if (!tabarraylen && !tabstops) 
                tabstops = qRound(fm.horizontalAdvance(u'x')*8);
            
         else if (chr == u'\\x9c') 
            // string with multiple length variants
            hasMoreLengthVariants = true;
            break;
        
    

    QList<QTextLayout::FormatRange> underlineFormats;
    int length = offset - old_offset;
    if ((hidemnmemonic || showmnemonic) && maxUnderlines > 0) 
        QChar *cout = text.data() + old_offset;
        QChar *cout0 = cout;
        QChar *cin = cout;
        int l = length;
        while (l) 
            if (*cin == u'&') 
                ++cin;
                --length;
                --l;
                if (!l)
                    break;
                if (*cin != u'&' && !hidemnmemonic && !(tf & Qt::TextDontPrint)) 
                    QTextLayout::FormatRange range;
                    range.start = cout - cout0;
                    range.length = 1;
                    range.format.setFontUnderline(true);
                    underlineFormats.append(range);
                
#ifdef Q_OS_MAC
             else if (hidemnmemonic && *cin == u'(' && l >= 4 &&
                       cin[1] == u'&' && cin[2] != u'&' &&
                       cin[3] == u')') 
                int n = 0;
                while ((cout - n) > cout0 && (cout - n - 1)->isSpace())
                    ++n;
                cout -= n;
                cin += 4;
                length -= n + 4;
                l -= 4;
                continue;
#endif //Q_OS_MAC
            
            *cout = *cin;
            ++cout;
            ++cin;
            --l;
        
    

以上是关于Qt中QPainter的使用的主要内容,如果未能解决你的问题,请参考以下文章

QT源码拾贝0-5(qimage和qpainter)

qt - 使用 QPainter 实例化绘图

Qt:在子部件上使用 QPainter

如何使用 Qpainter 在 Qt 中绘制棋盘

QT 5.7 QPainter 线对齐

Qt - 创建 QPainter