您的位置:首页 - HT - 正文
QT实例HovertreeDrawing使用QPainter画直线和文本
QT 实例

名称:HovertreeDrawing

实例介绍:
使用QPainter画直线和文本
按这个方法,可以画更多元素,例如曲线、圆等。

运行效果图:


开发环境:
Qt Creator 4.9.1 (Enterprise)

编译环境:
Qt 5.13.0 MSVC2017 32bit

步骤:




相关知识:
QT的绘图系统使用户可以在屏幕或者打印设备上用相同的API绘图,绘图系统基于QPainter、QPaintDevice和QPaintEngine类。
另外:QMainWindow继承自QWidget

实例源代码如下,附项目源码下载:
#include "htmainwindow.h"
#include "ui_htmainwindow.h"

#include <QPainter>
#include <QTextCodec>

HtMainWindow::HtMainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::HtMainWindow)
{
ui->setupUi(this);
setPalette(QPalette(Qt::white));//设置窗口为白色背景

QTextCodec *codec = QTextCodec::codecForName("GBK");
QString h_title=codec->toUnicode("\u0051\u0054\u0020\u4f7f\u7528\u0051\u0050\u0061\u0069\u006e\u0074\u0065\u0072\u0020\u753b\u76f4\u7ebf\u548c\u6587\u672c\u002d\u002d\u4f55\u95ee\u8d77");
this->setWindowTitle(h_title);
}

HtMainWindow::~HtMainWindow()
{
delete ui;
}


void HtMainWindow::paintEvent(QPaintEvent *event)
{
myDrawShape();
}


void HtMainWindow::myDrawShape()
{
QPainter h_HoverTreePainter(this);//创建QPainter对象
h_HoverTreePainter.setRenderHint(QPainter::Antialiasing);// 抗锯齿
h_HoverTreePainter.setRenderHint(QPainter::TextAntialiasing);// 抗锯齿

int W=this->width(); //绘图区宽度
int H=this->height(); //绘图区高度

//设置画笔
QPen pen;
pen.setWidth(1); //线宽
pen.setColor(Qt::black); //划线颜色

//Qt::NoPen,Qt::SolidLine, Qt::DashLine, Qt::DotLine,Qt::DashDotLine,Qt::DashDotDotLine,Qt::CustomDashLine
pen.setStyle(Qt::SolidLine);//线的类型,实线、虚线等

//Qt::FlatCap, Qt::SquareCap,Qt::RoundCap
pen.setCapStyle(Qt::FlatCap);//线端点样式

//Qt::MiterJoin,Qt::BevelJoin,Qt::RoundJoin,Qt::SvgMiterJoin
pen.setJoinStyle(Qt::BevelJoin);//线的连接点样式
h_HoverTreePainter.setPen(pen);


// drawLine
QLine h_line0(0,0,W,0);
h_HoverTreePainter.drawLine(h_line0);
QLine h_line1(0,H/5,W,H/5);
h_HoverTreePainter.drawLine(h_line1);
QLine h_line2(0,H*2/5,W,H*2/5);
h_HoverTreePainter.drawLine(h_line2);
QLine h_line3(0,H*3/5,W,H*3/5);
h_HoverTreePainter.drawLine(h_line3);
QLine h_line4(0,H*4/5,W,H*4/5);
h_HoverTreePainter.drawLine(h_line4);

QLine h_lineA(W/5,0,W/5,H);
h_HoverTreePainter.drawLine(h_lineA);
QLine h_lineB(W*2/5,0,W*2/5,H);
h_HoverTreePainter.drawLine(h_lineB);
QLine h_lineC(W*3/5,0,W*3/5,H);
h_HoverTreePainter.drawLine(h_lineC);
QLine h_lineD(W*4/5,0,W*4/5,H);
h_HoverTreePainter.drawLine(h_lineD);

h_HoverTreePainter.drawText(W*2/5, H*2/5+H/10, " hovertree.com ");
}

项目源码下载:HovertreeDrawing下载
下载地址2
提取码: 28gv

评论: