问题来源
我们从小学习的数学中是右手座标系,很多系统中(如:ros)也是右手系,而Qt Graphics View Framework 中却是左手座标系,当两个不同座标系的系统结合时,导致了界面上显示的内容和其他系统中的内容是上下翻转的,虽然看起来别扭,但是各种操作却不会有任何问题。
解决办法
方案一
在QGrahpicsView中将整个显示上下翻转,也就是座标系还是原来的座标系,但是显示上是上下翻转的,这样就很迅速的解决了问题。
GraphicsView::GraphicsView(QWidget *parent) : QGraphicsView(parent)
{
...
// NOTE:解决左手座标系和右手座标系的问题,Qt是左手座标系,算法是右手座标系,所以此处要将座标系的Y轴翻转
QTransform transform;
transform.setMatrix(1, 0, 0,
0, -1, 0,
0, 0, 1);
setTransform(transform);
}
当然这种解决方案也带来些小问题:
比如说:要将QRect的四个点的座标按照顺时针方向发给算法模块在座标系没有变换前,四个点发送的顺序是:rect.topLeft() => rect.topRight() => rect.bottomRight() => rect.bottomLeft()。但在座标系变换后,四个点发送顺序成了:rect.bottomLeft() => rect.bottomRight() => rect.topRight() => rect.topLeft()。
当然,你画的字体也是颠倒的,需要手动将其翻转。
void GraphicsRectItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
QGraphicsRectItem::paint(painter, option, widget);
// 将文本翻转
QTransform transform;
transform.setMatrix(1, 0, 0,
0, -1, 0,
0, rect().center().y() * 2, 1);
painter->setTransform(transform, true);
painter->drawText(rect(), Qt::AlignCenter, QObject::tr("静态区域"));
}
方案二
在Qt和算法接口模块中实现两个函数,QPointF mapToScene(const QPointF &point)和QPointF mapFromScene(const QPointF &point),凡是进入Qt的座标都调用一次mapToScene(),凡是从Qt出去的座标调用一次mapFromScene(),这样能完美解决问题,但是会有些复杂。