May-26-2024, 03:31 PM
(This post was last modified: May-26-2024, 03:32 PM by MasterIphone.)
I'm not completely new to Python, but I'm faced with a difficult problem for me.
Previously I wrote parsers and file converters.
Now I need to work with SVG files and I can’t find a solution.
I wrote this code using the Qt5 framework.
its text is like this:
I'll ask the community for help on how to do this.
Perhaps you need to change the text of the SVG file itself and also change the code of the main file.
I'd be grateful for any hints.
Previously I wrote parsers and file converters.
Now I need to work with SVG files and I can’t find a solution.
I wrote this code using the Qt5 framework.
# python3 animated_svg.py import sys from PyQt5.QtWidgets import QApplication, QMainWindow, QGraphicsScene, QGraphicsView from PyQt5.QtCore import Qt, QTimer from PyQt5.QtSvg import QGraphicsSvgItem class MainWindow(QMainWindow): def __init__(self): super().__init__() # Create scene and view self.scene = QGraphicsScene() self.view = QGraphicsView(self.scene) self.setCentralWidget(self.view) # Set screen size self.view.setFixedSize(700, 700) # Load SVG file with a line self.svg_item = QGraphicsSvgItem("two_lines.svg") self.scene.addItem(self.svg_item) # Find the center of the line line_center = self.svg_item.boundingRect().center() # Set the rotation origin point to the center of the line self.svg_item.setTransformOriginPoint(line_center) # Create initial parameters for line rotation self.angle = 0 # Initial rotation angle self.direction = 1 # Rotation direction: 1 - right, -1 - left # Create a timer for animation self.timer = QTimer(self) self.timer.timeout.connect(self.rotateLine) self.timer.start(50) # Interval in milliseconds def rotateLine(self): # Increase or decrease the rotation angle self.angle += self.direction * 1 # Change the angle by 1 degree # Check if we have reached the extreme angle values if self.angle >= 45: self.angle = 45 self.direction = -1 # Change direction to left elif self.angle <= -45: self.angle = -45 self.direction = 1 # Change direction to right # Rotate the line self.svg_item.setRotation(self.angle) if __name__ == "__main__": app = QApplication(sys.argv) mainWindow = MainWindow() mainWindow.show() sys.exit(app.exec_())added two_lines.svg as a separate file
its text is like this:
Output:<svg xmlns="http://www.w3.org/2000/svg">
<g id="horizontal_line">
<line x1="25" y1="100" x2="425" y2="100" stroke="black" stroke-width="2" />
</g>
<g id="vertical_line">
<line x1="225" y1="50" x2="225" y2="150" stroke="red" stroke-width="2" />
</g>
</svg>
After running the code, I just see the rotation of two lines, although I planned to rotate only one line with id="horizontal_line"I'll ask the community for help on how to do this.
Perhaps you need to change the text of the SVG file itself and also change the code of the main file.
I'd be grateful for any hints.