欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Qt开源-直方图

程序员文章站 2024-03-19 18:44:04
...

话不多说,先上效果图:

Qt开源-直方图

QPainter绘制部分:

QPainter painter(this);

    painter.translate(50, this->height() - 50);
    painter.rotate(270);

    qint16 ny = 0;
    for (auto result : m_listAnswerResult) {
        // histogram
        if (result.correct) {
            painter.setPen(QColor(35, 199, 108));
            painter.setBrush(QColor(35, 199, 108));
        } else {
            painter.setPen(QColor(239, 76, 79));
            painter.setBrush(QColor(239, 76, 79));
        }

        ny += kHorizontalSpacing + kHistogramWidth;
        if (result.count > 0) {
            painter.drawRect(40, ny, result.count * getPerHeightSize(), kHistogramWidth);
        }

        // choice
        painter.save();
        QFont choice_font("Microsoft YaHei", 20, 500);
        QFontMetrics fm_choice(choice_font);

        // choice text width(for align center)
        int choice_width  = fm_choice.boundingRect(result.choice).width();
        int choice_height = fm_choice.boundingRect(result.choice).height();
        painter.translate(0, ny + (kHistogramWidth - choice_width) / 2);
        painter.rotate(90);

        painter.setFont(choice_font);
        painter.setPen(QColor(51, 51, 51));
        painter.drawText(0, 0, result.choice);
        painter.restore();

        // count
        painter.save();
        QFont count_font("Microsoft YaHei", 14, 400);
        QFontMetrics fm_count(count_font);

        // count text width(for align center)
        int text_width = fm_count.boundingRect(QString::number(result.count)).width();
        painter.translate(choice_height + result.count * getPerHeightSize() + kCountSpacing, ny + (kHistogramWidth - text_width) / 2);
        painter.rotate(90);

        painter.setFont(count_font);
        painter.setPen(QColor(102,102,102));
        painter.drawText(0, 0, QString::number(result.count));
        painter.restore();
    }

开源代码:

转载请注明出处,谢谢