前面一张文章介绍过在利用QPainter接口画可拖动的圆,通过官方介绍:
Graphics in Qt 5 is primarily done either through the imperative QPainter API, or through Qt’s declarative UI language, Qt Quick, and its scene graph back-end.
我们知道在Qt5中使用Qt Quick模块也可以实现简单图形的绘制。可是当我们需要在QML中实现坐标轴的时候,感觉用QtQuick实现起来有点力不从心了。不过先别沮丧,看看这个QQuickPaintedItem:
The QQuickPaintedItem class provides a way to use the QPainter API in the QML Scene Graph.
Qt的大牛应该考虑到了QtQuick的不足了,有了这个东东,你就可以在QML上发挥你的想象力了。
我继承了QQuickPaintedItem,实现了它的paint方法,在此方法里画坐标轴及添加曲线。代码如下:
void QAxis::paint(QPainter *painter)
{
m_painter = painter;
//随坐标轴取值范围变化,更新坐标标签及其位置
if(m_xAutoScale)
upDateXLabels();
if(m_yAutoScale)
upDateYLabels();
initXYState();
m_painter->setRenderHint(QPainter::Antialiasing);
QMap::const_iterator cur;
for(cur=m_curveList.begin(); cur!=m_curveList.end(); cur++)
{
for(int j=0; jgetDataSize(); j++)
{
QPointF tmp = cur.value()->getPosData(j);
m_painter->setPen(cur.value()->getPointPen());
m_painter->drawEllipse(tmp.x()-1, tmp.y()-1, 2, 2);
//draw curve title
if(j == cur.value()->getDataSize() - 1)
{
if(cur.value()->getTitleShow())
{
QPen pen;
pen.setColor(Qt::red);
m_painter->setPen(pen);
double x = tmp.x()+8;
double y = tmp.y();
if(x > m_xPosMax - 20)
x = x - 25;
if(y > m_yPosMax - 20)
y = y - 25;
m_painter->drawText(QPointF(x, y), cur.value()->getTitle());
}
break;
}
m_painter->setPen(cur.value()->getLinePen());
m_painter->drawLine(cur.value()->getPosData(j), cur.value()->getPosData(j+1));
}
}
}
在QML中显示坐标轴:
import QtQuick 2.3
import QtQuick.Window 2.0
import QtQuick.Controls 1.1
//import QtQuick.Controls.Styles 1.1
import QtQml 2.2
import com.robinson.qaxis 1.0
ApplicationWindow {
id: mainWindow
visible: true
width: Screen.width/2
height: Screen.height/2
QAxis {
id: qAxis
anchors.fill: parent
Component.onCompleted: {
//setDirection("down");
setXValueRange(0, 10);
setYValueRange(0, 10);
setXLabels("0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10");
setYLabels("0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10");
setAutoScale("X", true);
setAutoScale("Y", true);
addCurve("testCurve");
setGridShow(true);
addData("testCurve", 0, 0);
addData("testCurve", 2, 2);
addData("testCurve", 5, 3);
}
}
//使坐标轴自适应窗口大小
onWidthChanged: qAxis.setAxisSize(mainWindow.width, mainWindow.height);
onHeightChanged: qAxis.setAxisSize(mainWindow.width, mainWindow.height);
}
最后看下效果图:
源码下载地址1:CSDN
源码下载地址2:https://github.com/RobinsonSir/QmlQAxis