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

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

相关推荐
rainbow_lucky01062 小时前
Word-like编辑器
qt·编辑器·word-like
开始了码3 小时前
QT::对话框:颜色对话框2
qt
穆雄雄3 小时前
Qt-for-鸿蒙PC Slider 组件开源鸿蒙开发实践
qt·开源·harmonyos
国服第二切图仔13 小时前
Qt-for-鸿蒙PC-多线程绘制开源鸿蒙开发实践
qt·开源·鸿蒙pc
国服第二切图仔15 小时前
Qt-for-鸿蒙PC-CheckBox开源鸿蒙开发实践
qt·开源·鸿蒙pc
喵个咪17 小时前
Qt 优雅实现线程安全单例模式(模板化 + 自动清理)
c++·后端·qt
离离茶21 小时前
【笔记1-8】Qt bug记录:QListWidget窗口的浏览模式切换为ListMode后,滚轮滚动速度变慢
笔记·qt·bug
共享家95271 天前
QT-系统(文件)
开发语言·qt·命令模式
IT从业者张某某1 天前
Qt-for-鸿蒙PC-TextEditorPro 多功能文本编辑器开源鸿蒙开发实践
qt·开源·harmonyos
IT从业者张某某1 天前
Qt-for-鸿蒙PC-验证码组件开发实战
开发语言·qt·harmonyos