Home > Net >  Drawing point of view for an object in PyQt6
Drawing point of view for an object in PyQt6

Time:11-24

I'm really new to PyQt6. I want to draw an object that moves in space and draw around it its point of view site. This is exactly what I want:

what I want to draw

And this is what I get till now.

from PyQt6.QtWidgets import *
from PyQt6.QtCore import *
from PyQt6.QtGui import *
import sys

class Window(QWidget):
    def __init__(self):
        super().__init__()
        self.painter = QPainter(self)
        self.setWindowTitle("test 5")
        self.setStyleSheet("background-color:rgb(20, 20, 20);font-size:20px;")
        self.setGeometry(0, 0, 600, 600)

    def paintEvent(self, event):
        self.painter.begin(self)
        self.painter.setPen(QPen(QColor(30, 130, 30),  0, Qt.PenStyle.SolidLine))
        self.painter.setBrush(QBrush(QColor(0, 100, 0), Qt.BrushStyle.SolidPattern))
        self.painter.translate(300, 300)
        self.painter.rotate(-90)
        path = QPainterPath()
        path.moveTo(-20, 0)
        path.lineTo(-30, 15)
        path.lineTo(20, 0)
        path.lineTo(-30, -15)
        path.lineTo(-20, 0)
        self.painter.drawPath(path)
        self.painter.setPen(QPen(QColor(130, 30, 30),  0, Qt.PenStyle.SolidLine))
        self.painter.setBrush(QBrush(QColor(100, 0, 0, 100), Qt.BrushStyle.SolidPattern))
        path = QPainterPath()
        path.moveTo(100, 0)
        path.arcTo(-100, -100, 200, 200, -90 /2 * 16, 180 * 16)
        self.painter.drawPath(path)
        self.painter.end()

if __name__ == "__main__":
    App = QApplication(sys.argv)
    window = Window()
    window.show()
    try:
        sys.exit(App.exec())
    except SystemExit:
        print("closing window ...")

I want to draw an arc around the object but it draws a full circle.

CodePudding user response:

You're using the wrong angle for QPainterPath, which uses degrees, as opposed to QPainter which uses sixteenths of a degree.

Also, you need to use arcMoveTo() (not moveTo) in order to place the path at the correct position when starting a new arc.

Finally, you have to close the path, using closeSubpath().

        path = QPainterPath()
        outRect = QRectF(-100, -100, 200, 200)
        path.arcMoveTo(outRect, -60)
        path.arcTo(outRect, -60, 120)
        path.arcTo(-50, -50, 100, 100, 60, 240)
        path.closeSubpath()

        painter.drawPath(path)
  • Related