-1

Hi I'm creating a network diagrame of nodes using networkX's circular layout. It's been great laying out nodes in a circle however I want to add text to each node(a description) but the text must not overlap, so it remains readable something like this textwheel. Notice how all the text juts outward from each node. How can i do the same. I'm using pyqt/qt and I know of the painter.rotate method but I can't have a fixed rotation, what's the best way to workout the correct rotation for each node's description. I'm drawing the nodes on a Qgraphicsscene, so I can get the boundingRect of the scene, and also get the center of the scene. I can also get the position of each node as output by NetworkX's cirular layout. Having the 2 points is a start. I'm not sure what the best way forward after that is. If there are several articles that demonstrate a good solution please let me. One additional wrinkle is that the nodes themselves can be moved by the user. But I imagine that once I've worked out how to draw the text, i can apply the same formula/method in the event that the node itself is moved by the user. Just need a general way of working out the angle of the center of the node in relation to the center of the graphicssene. If there are code samples that can point me in the right direction please share.

Thanks

user595985
  • 1,543
  • 4
  • 29
  • 55

1 Answers1

1

Usually, the rotation of the text is the same as the rotation of the radius used to position the reference point on the text's rectangle.

The code below demonstrates how to use painter transforms to easily achieve the desired result. The text alignment trick is inspired by this answer.

screenshot of the example

import sys
from PyQt5.QtCore import QRect, QRectF, QSizeF, QPointF, Qt
from PyQt5.QtGui import QPainter, QPicture, QFont, QColor
from PyQt5.QtWidgets import QApplication, QLabel

def drawNode(painter, angle, radius, text):
    size = 32767.0;
    painter.save();
    painter.rotate(-angle);
    painter.translate(radius, 0);
    painter.drawText(QRectF(0, -size/2.0, size, size), Qt.AlignVCenter, text);
    painter.restore();

if __name__ == "__main__":
    app = QApplication(sys.argv)

    pic = QPicture()
    pic.setBoundingRect(QRect(-100, -100, 200, 200))
    p = QPainter(pic)

    p.drawEllipse(0, 0, 3, 3)
    p.setFont(QFont("Helvetica", 25))
    for angle in range(0, 359, 30):
        drawNode(p, angle, 50, str(angle))
    p.end()

    l = QLabel()
    l.setPicture(pic);
    l.show();

    sys.exit(app.exec_())
Community
  • 1
  • 1
Kuba hasn't forgotten Monica
  • 95,931
  • 16
  • 151
  • 313