Search code examples
c++qtdrawingqgraphicssceneqpainter

Drawing of infinite line in Qt


I have some problem with drawing in Qt.

I need to draw a infinite line on QGraphicsScene with QPainter. And about line I know only base point and line direction (or base point and one more point, that lays on this line).

In result, I need something like that.

But I didn't find any solutions or something close to my problem. I hope that someone faced with similar problem and can help me. Thank you in advance for all your recommends.


Solution

  • You can assume that an infinite line is a line which the start and end points are outside the scene.

    If you calculate the diagonal length of your scene, you have the maximum visible length of any line.

    After that, you can use QLineF to create your "infinite" line.

    An example with PyQt5:

    direction = -45
    basePoint = QPointF(200, 200)
    
    maxLength = math.sqrt(scene.width() ** 2 * scene.height() ** 2)
    
    line1 = QLineF(basePoint, basePoint + QPointF(1, 0)) # Avoid an invalid line
    line2 = QLineF(basePoint, basePoint + QPointF(1, 0))
    
    # Find the first point outside the scene
    line1.setLength(maxLength / 2)
    line1.setAngle(direction)
    
    # Find the sceond point outside the scene
    line2.setLength(maxLength / 2)
    line2.setAngle(direction + 180)
    
    # Make a new line with the two end points
    line = QLineF(line1.p2(), line2.p2())
    
    scene.addItem(QGraphicsLineItem(line))