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);
}

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

相关推荐
San813_LDD5 小时前
[QT]《Qt 开发避坑指南:随机数、容器操作与 VS 环境配置》
开发语言·qt
稷下元歌11 小时前
七天学会plc加机器视觉之AI 接入 外设模块开发全详细操作文档(全程配套视频按文档实操)
python·sql·qt·贪心算法·r语言·wpf·时序数据库
艾莉丝努力练剑12 小时前
【QT】界面优化:QSS
linux·运维·开发语言·网络·qt·计算机网络·udp
雪的季节12 小时前
Qt 自定义表头
开发语言·qt
艾莉丝努力练剑13 小时前
【QT】系统相关:QT文件
linux·服务器·开发语言·网络·qt·tcp/ip·计算机网络
爱思考的小伙1 天前
Qt-03:串口助手
qt
864记忆1 天前
远程执行指令-常用指令集
qt
郝学胜_神的一滴1 天前
Qt 高级开发 026:QTabWidget御道,从筑基到化境
c++·qt
走好每一步1 天前
2、VDK 使用QVTKOpenGLNativeWidget嵌入到QT窗体中
qt·vtk·三维图像
nnnnichijou1 天前
Qt 6.9 嵌入式 Linux 交叉编译全栈填坑指南(以树莓派5 AArch64 为例
qt·嵌入式·交叉编译·qml·树莓派5