Qt-interest Archive, April 2008
QGraphicsView intersection point of lines
Message 1 in thread
Hello,
i just wanted to mark the point where a line crosses a (line of a)
rectangle. It's impelmented like in the code attached - but the
intersection point is always drawn somewhere (look at screenshot).
Anybody got any idea why? And how to do it correct?
Thx,
RZ
#include <QtGui/QApplication>
#include <QGraphicsRectItem>
#include <QGraphicsScene>
#include <QPainter>
#include "gv.h"
class GELineItem : public QGraphicsLineItem
{
public:
GELineItem(int x1, int y1, int x2, int y2) : QGraphicsLineItem(x1, y1,
x2, y2) {}
enum {Type = UserType + 1};
int GELineItem::type() const {return Type;}
};
class GERectItem : public QGraphicsRectItem
{
public:
GERectItem::GERectItem(int x, int y, int w, int h)
: QGraphicsRectItem(x, y, w, h)
{
setFlag(QGraphicsItem::ItemIsSelectable);
setFlag(QGraphicsItem::ItemIsMovable);
}
private:
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option,
QWidget *widget)
{
painter->drawRoundedRect(rect().x(), rect().y(), rect().width(),
rect().height(), 5, 5);
QPointF intersectPoint;
QList<QGraphicsItem *> colList = collidingItems();
for (int i = 0; i < colList.count(); i++)
{
if (colList.at(i)->type() == GELineItem::Type)
{
QLineF l1(rect().topLeft().x(), rect().topLeft().y(),
rect().topRight().x(), rect().topRight().y());
painter->setPen(QPen(QBrush(QColor(0, 0, 255)), 2));
painter->drawLine(l1);
QLineF::IntersectType intersectType =
dynamic_cast<GELineItem*>(colList.at(i))->line().intersect(l1,
&intersectPoint);
//if (intersectType == QLineF::BoundedIntersection)
if (!intersectPoint.isNull())
{
painter->setPen(QPen(QBrush(QColor(0, 0, 255)), 2));
painter->drawEllipse(intersectPoint.x(), intersectPoint.y(), 5, 5);
break;
}
}
}
}
};
gv::gv(QWidget *parent, Qt::WFlags flags)
: QMainWindow(parent, flags)
{
ui.setupUi(this);
QGraphicsScene *scene = new QGraphicsScene(this);
scene->setItemIndexMethod(QGraphicsScene::NoIndex);
ui.graphicsView->setScene(scene);
ui.graphicsView->setCacheMode(QGraphicsView::CacheBackground);
ui.graphicsView->setViewportUpdateMode(QGraphicsView::BoundingRectViewportUpdate);
GELineItem *line = new GELineItem(20, 20, 20, 320);
scene->addItem(line);
GERectItem *ri = new GERectItem(0, 0, 150, 50);
ri->setPos(250, 250);
scene->addItem(ri);
}
gv::~gv()
{
}
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
gv w;
w.show();
a.connect(&a, SIGNAL(lastWindowClosed()), &a, SLOT(quit()));
return a.exec();
}

