QT 带箭头的控件QPolygon

由于对当前项目需要绘制一个箭头控件,所以使用了QPainter和QPolygon来进行绘制,原理就是计算填充,下面贴出代码和效果图

这里简单介绍下QPolygon

QPolygon是继承自

C++ 复制代码
QVector<QPoint>

那么可以很简单的理解为,他就是一个点的集合

所以由3个点就构成了一个箭头,当然更复杂的箭头大家可以自己去进行构建,由于我的项目需要的只是单纯箭头就展现如下代码,我还填充了一个矩形框作为背景。

C++ 复制代码
void arrowWidget::paintEvent(QPaintEvent* event)
{
    QPainter painter(this);
    painter.setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing);
    int cornerRadius = qMin(this->width(), this->height()) / 10; 

    
    QRect rect(10, 10, this->width() - 20, this->height() - 20); 
    painter.setPen(Qt::NoPen);
    painter.setBrush(QColor(85, 114, 128));  
    painter.drawRoundedRect(rect, cornerRadius, cornerRadius);   
    painter.setBrush(Qt::lightGray); 
    //drawcaricon(&painter);

    if (leftArrow)
        drawLeftArraow(&painter);
    else
        drawRightArrow(&painter);
}


void arrowWidget::drawLeftArraow(QPainter* painter)
{

    QPoint center(this->width() / 2, this->height() / 2);

    
    int arrowWidth = this->width() * 0.2; 
    int arrowHeight = this->height() * 0.2; 


    QPoint left(center.x() - arrowWidth, center.y());    
    QPoint top(center.x() + arrowWidth / 2, center.y() - arrowHeight); 
    QPoint bottom(center.x() + arrowWidth / 2, center.y() + arrowHeight);


    QPolygon arrow;
    arrow << left << top << bottom;

 
    painter->drawPolygon(arrow);
}

void arrowWidget::drawRightArrow(QPainter* painter)
{

    QPoint center(this->width() / 2, this->height() / 2);

   
    int arrowWidth = this->width() * 0.2; 
    int arrowHeight = this->height() * 0.2;


    QPoint right(center.x() + arrowWidth, center.y());   
    QPoint top(center.x() - arrowWidth / 2, center.y() - arrowHeight); 
    QPoint bottom(center.x() - arrowWidth / 2, center.y() + arrowHeight); 


    QPolygon arrow;
    arrow << right << top << bottom;

    painter->drawPolygon(arrow);
}

这是效果图,有需要其他操作的可以自己根据实际情况调整。

相关推荐
小短腿的代码世界2 分钟前
Qt Concurrent 深度解析:并发编程范式与源码级实现原理
qt·系统架构·lucene
Ulyanov4 小时前
《PySide6 GUI开发指南:QML核心与实践》 第一篇:GUI新纪元——QML与PySide6生态系统全景
开发语言·python·qt·qml·雷达电子对抗
Drone_xjw8 小时前
解决 Qt 程序在 Kylin(麒麟)系统下表头“白屏”的问题
开发语言·qt·kylin
米优10 小时前
qt+gstreamer实现播放功能
qt·gstreamer
zjun100110 小时前
QT:语言翻译
开发语言·qt
-凌凌漆-12 小时前
【Qt】const QString &与QString的区别
开发语言·qt
Drone_xjw12 小时前
Qt QTableView 表头变白问题(Kylin/UKUI系统)原因分析与解决方案
开发语言·qt·kylin
mabing99312 小时前
Qt 实现自定义分段控制器
开发语言·qt
誰能久伴不乏12 小时前
Qt 混合编程核心原理:C++ 与 QML 通信机制详解
linux·c++·qt·架构·状态模式
sycmancia13 小时前
Qt——文本编辑器中的数据存取
开发语言·qt