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

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

相关推荐
dot to one21 分钟前
Qt 中 QWidget涉及的常用核心属性介绍
开发语言·c++·qt
码农新猿类1 小时前
初入OpenCV
qt·opencv·计算机视觉
洛克希德马丁3 小时前
QLineEdit增加点击回显功能
c++·qt·ui
向日葵xyz4 小时前
Qt5与现代OpenGL学习(十一)OpenGL Widget鼠标控制直线旋转
开发语言·qt·学习
小宋加油啊6 小时前
Mac QT水平布局和垂直布局
开发语言·qt·macos
伐尘17 小时前
【Qt】编译 Qt 5.15.x For Windows 基础教程 Visual Studio 2019 MSVC142 x64
windows·qt·visual studio
吃面不喝汤6618 小时前
破解 Qt QProcess 在 Release 模式下的“卡死”之谜
开发语言·qt
charlie1145141911 天前
逐步理解Qt信号与槽机制
数据库·qt
yaso_zhang1 天前
当生产了~/qt-arm/bin/qmake,可以单独编译其他-源码的某个模块,如下,编译/qtmultimedia
qt
code bean1 天前
【Qt/C++】深入理解 Lambda 表达式与 `mutable` 关键字的使用
开发语言·c++·qt