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

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

相关推荐
阿猿收手吧!4 小时前
【QT】QPixmap QImage QBitmap QPicture
开发语言·c++·qt
明月醉窗台7 小时前
Qt 入门 0 之 QtCreator 简介
开发语言·c++·windows·qt
C语言小火车10 小时前
QT面试题:内存管理与对象生命周期
开发语言·qt·面试
追烽少年x16 小时前
使用QAction编辑器添加QAction到ui里
qt
Truelon19 小时前
【QT】QT编译链接 msql 数据库
数据库·qt
864记忆1 天前
车辆视频检测器linux版对于密码中包含敏感字符的处理方法
linux·qt
努力搬砖的咸鱼1 天前
QTSql全解析:从连接到查询的数据库集成指南
数据库·qt
EverestVIP1 天前
Qt 自带的QSqlDatabase 模块中使用的 SQLite 和 SQLite 官方提供的 C 语言版本(sqlite.org)对比
c语言·qt·sqlite
永不停转1 天前
C++宏定义中可变参数列表__VA_ARGS__ 及 QT 提供的宏 QT_OVERLOADED_MACRO
c++·qt
追烽少年x1 天前
Qt中自定义插件和库(1)
qt