重写paintEvent事件,代码如下
```
void xx::paintEvent(QPaintEvent *event){
QPainter painter(this);
//绘制x,y轴,_maxWidth为y轴边距
painter.drawLine(QPoint(_maxWidth,20),QPoint(width(),20));
painter.drawLine(QPoint(_maxWidth, 20), QPoint(_maxWidth,height()));
//绘制刻度,_maxMinutes为x轴最大刻度
int num = (_maxMinutes - _minMinutes) / 5;
int interval = (width() - _maxWidth) / num;
for (int index = 0; index != num;++index){
painter.drawLine(QPoint(_maxWidth + index * interval, 20), QPoint(_maxWidth + index * interval, 15));
painter.drawText(QPoint(_maxWidth + index * interval, 10), QString::number(_minMinutes + index*5));
}
num = _dataMap.size();
interval = (height() - 20) / (num + 2);
//绘制数据_dataMap,QString(y轴坐标名称:起始时间-结束时间& 起始时间-结束时间)
QMap<int, QString>::iterator it = _dataMap.begin();
int index = 1;
for (; it != _dataMap.end(); ++it){
QStringList list = it.value().split(":");
if (list.size() != 2) continue;
painter.drawText(QPoint(0, 20 + interval * index), list[0]);
painter.drawLine(QPoint(_maxWidth, 20 + interval * index), QPoint(_maxWidth + 5, 20 + interval * index));
for each (QString var in list[1].split("&")){
if (var.isEmpty()) continue;
QStringList interalList = var.split("-");
if (interalList.size() != 2) continue;
int x = (interalList[0].toDouble() / _maxMinutes) * (width() - _maxWidth);
int x1 = (interalList[1].toDouble() / _maxMinutes) * (width() - _maxWidth);
painter.drawLine(QPoint(_maxWidth + x, 20 + interval * index), QPoint(_maxWidth + x1, 20 + interval * index));
}
++index;
}
}
```
效果如下
已经工作的程序员朋友可以关注下我的gzh“程序员成长日志”,分享日常工作中解决的问题即可赚取稿费,大家一起成长~