1

У меня есть небольшой скрипт для самодельного растрового редактора и мне необходимо реализовать функцию рисования мышью на изображении.

Решение под комментарием вызывает ошибку:

Process finished with exit code -1073740791 (0xC0000409).

Что можно исправить в инициализации изображения или в самой функции рисования для того, чтобы не вызывалась ошибка?

import sys
from PyQt5 import uic
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PIL import Image, ImageDraw
from PIL.ImageQt import ImageQt


class MainWindow(QMainWindow):
    """ Блок инициализации """

    def __init__(self):
        super().__init__()
        uic.loadUi('untitled.ui', self)

        self.scale = 0

        self.openFile()

        self.image = Image.open(self.file)
        self.a = ImageQt(self.image)
        self.pixmap = QPixmap.fromImage(self.a)

        self.drawingFlag = True
        self.brushColor = Qt.black
        self.brushWidth = 1

        self.toolButton2Load.clicked.connect(self.openFile)
        self.shortcutLoad = QShortcut(QKeySequence("Ctrl+L"), self)
        self.shortcutLoad.activated.connect(self.openFile)

        self.toolButton1Zoom.clicked.connect(self.scaleImageBigger)
        self.toolButton2Zoom.clicked.connect(self.scaleImageSmaller)

        self.toolButton3Return.clicked.connect(self.scaleImageReturn)
        self.shortcutReturn = QShortcut(QKeySequence("Ctrl+Z"), self)
        self.shortcutReturn.activated.connect(self.scaleImageReturn)

        self.setMouseTracking(True)

        self.initUI()

    def initUI(self):
        self.imageSizeX = self.image.size[0]
        self.startImageSizeX = self.image.size[0]
        self.imageSizeY = self.image.size[1]
        self.startImageSizeY = self.image.size[1]

        self.labelSize.setText(f'{self.imageSizeX}x{self.imageSizeY}')
        self.labelImage.resize(self.imageSizeX, self.imageSizeY)
        self.labelImage.setPixmap(self.pixmap)

    # ╔══════════════════════════════════════════════════════════════════════╗
    # ║Блок функций                                                          ║
    # ╚══════════════════════════════════════════════════════════════════════╝

    def openFile(self):  # Функция открытия файла
        self.file = QFileDialog.getOpenFileName(
            self, 'Выбрать картинку', '',
            'Картинка (*.jpg);;Картинка (*.png);;Все файлы (*)')[0]

        self.pixmap = QPixmap(self.file)
        self.image = Image.open(self.file)
        self.initUI()

        self.pixmap = QPixmap(self.file)
        self.image = Image.open(self.file)
        self.initUI()

    def scaleImageBigger(self):  # Функция увеличения изображения
        if self.imageSizeX < 5001 and self.imageSizeY < 5001:
            self.imageSizeX *= 2
            self.imageSizeY *= 2
            self.scale += 1
            self.pixmap = self.pixmap.scaledToWidth(self.imageSizeX)

            self.labelImage.resize(self.imageSizeX, self.imageSizeY)
            self.labelImage.move(0, 131)
            self.labelSize.setText(f'{self.imageSizeX}x{self.imageSizeY}')
            self.labelImage.setPixmap(self.pixmap)

    def scaleImageSmaller(self):  # Функция уменьшения изображения
        if self.imageSizeX // 2 >= self.startImageSizeX and self.imageSizeY // 2 >= self.startImageSizeY:
            self.imageSizeX //= 2
            self.imageSizeY //= 2
            self.scale -= 1
            self.pixmap = self.pixmap.scaledToWidth(self.imageSizeX)

            self.labelImage.resize(self.imageSizeX, self.imageSizeY)
            self.labelImage.move(0, 131)
            self.labelSize.setText(f'{self.imageSizeX}x{self.imageSizeY}')
            self.labelImage.setPixmap(self.pixmap)

    def scaleImageReturn(self):  # Восстановление масштаба изображения
        self.imageSizeX = self.startImageSizeX
        self.imageSizeY = self.startImageSizeY
        self.scale = 0
        self.pixmap = self.pixmap.scaledToWidth(self.imageSizeX)

        self.labelImage.resize(self.imageSizeX, self.imageSizeY)
        self.labelImage.move(0, 131)
        self.labelSize.setText(f'{self.imageSizeX}x{self.imageSizeY}')
        self.labelImage.setPixmap(self.pixmap)

    def paintEvent(self, event):
        pass
        # painter = QPainter(self)
        # painter.drawPixmap(self.rect(), self.pixmap)

    # ╔══════════════════════════════════════════════════════════════════════╗
    # ║ Блок управления                                                      ║
    # ╚══════════════════════════════════════════════════════════════════════╝

    def mousePressEvent(self, event):
        pass
        # if (event.button() == Qt.LeftButton) and self.drawingFlag:
            # self.lastPoint = event.pos()

    def mouseMoveEvent(self, event):  # Событие движения мыши
        coordX = event.x()
        coordY = event.y() - 121
        if coordY < 0:
            coordY = 0
        self.labelCoords.setText(f"{coordX}, {coordY}")

        # if (event.buttons() & Qt.LeftButton) and self.drawingFlag:
            # painter = QPainter(self.pixmap)
            # painter.setPen(QPen(self.brushColor, self.brushWidthWidth,
            #                    Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin))
            # painter.drawLine(self.lastPoint, event.pos())
            # self.lastPoint = event.pos()
            # self.update()

    def wheelEvent(self, event):  # Событие вращения колеса мыши
        numDegrees = event.angleDelta().y() / 8
        numSteps = numDegrees // 15
        if numSteps > 0:
            self.scaleImageBigger()
        elif numSteps < 0:
            self.scaleImageSmaller()

        event.accept()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    mw = MainWindow()
    mw.show()
    sys.exit(app.exec_())

drawingFlag - переключение, которое будет происходить по кнопке и активировать/деактивировать рисование (сейчас всегда включено) brushColor и brushWidth пока нигде не реализованы.

untitled.ui:

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>MainWindow</class>
 <widget class="QMainWindow" name="MainWindow">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>1925</width>
    <height>1035</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>MainWindow</string>
  </property>
  <widget class="QWidget" name="centralwidget">
   <widget class="QTabWidget" name="tabWidget">
    <property name="geometry">
     <rect>
      <x>0</x>
      <y>0</y>
      <width>1920</width>
      <height>131</height>
     </rect>
    </property>
    <property name="currentIndex">
     <number>1</number>
    </property>
    <widget class="QWidget" name="tab1File">
     <attribute name="title">
      <string>Tab 1</string>
     </attribute>
    </widget>
    <widget class="QWidget" name="tab2Main">
     <property name="toolTip">
      <string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;Главная&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
     </property>
     <property name="whatsThis">
      <string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;Главна&lt;/p&gt;&lt;p&gt;&lt;br/&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
     </property>
     <property name="styleSheet">
      <string notr="true">Главная</string>
     </property>
     <attribute name="title">
      <string>Tab 2</string>
     </attribute>
     <widget class="QGroupBox" name="groupBox1">
      <property name="geometry">
       <rect>
        <x>10</x>
        <y>10</y>
        <width>51</width>
        <height>71</height>
       </rect>
      </property>
      <property name="title">
       <string/>
      </property>
      <widget class="QToolButton" name="toolButton1Save">
       <property name="geometry">
        <rect>
         <x>0</x>
         <y>0</y>
         <width>51</width>
         <height>51</height>
        </rect>
       </property>
       <property name="text">
        <string>S</string>
       </property>
      </widget>
      <widget class="QToolButton" name="toolButton2Load">
       <property name="geometry">
        <rect>
         <x>0</x>
         <y>50</y>
         <width>51</width>
         <height>22</height>
        </rect>
       </property>
       <property name="text">
        <string>Load</string>
       </property>
      </widget>
     </widget>
     <widget class="QLabel" name="label1">
      <property name="geometry">
       <rect>
        <x>10</x>
        <y>80</y>
        <width>151</width>
        <height>22</height>
       </rect>
      </property>
      <property name="text">
       <string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p align=&quot;center&quot;&gt;Буфер обмена&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
      </property>
     </widget>
     <widget class="QGroupBox" name="groupBox2">
      <property name="geometry">
       <rect>
        <x>70</x>
        <y>10</y>
        <width>91</width>
        <height>44</height>
       </rect>
      </property>
      <property name="title">
       <string/>
      </property>
      <widget class="QToolButton" name="toolButton1Copy">
       <property name="geometry">
        <rect>
         <x>0</x>
         <y>0</y>
         <width>91</width>
         <height>22</height>
        </rect>
       </property>
       <property name="text">
        <string>Копировать</string>
       </property>
      </widget>
      <widget class="QToolButton" name="toolButton2Cut">
       <property name="geometry">
        <rect>
         <x>0</x>
         <y>21</y>
         <width>91</width>
         <height>22</height>
        </rect>
       </property>
       <property name="text">
        <string>Вырезать</string>
       </property>
      </widget>
     </widget>
     <widget class="Line" name="linev1">
      <property name="geometry">
       <rect>
        <x>170</x>
        <y>0</y>
        <width>3</width>
        <height>101</height>
       </rect>
      </property>
      <property name="orientation">
       <enum>Qt::Vertical</enum>
      </property>
     </widget>
     <widget class="QGroupBox" name="groupBox3">
      <property name="geometry">
       <rect>
        <x>180</x>
        <y>10</y>
        <width>51</width>
        <height>71</height>
       </rect>
      </property>
      <property name="title">
       <string/>
      </property>
      <widget class="QToolButton" name="toolButton1Select">
       <property name="geometry">
        <rect>
         <x>0</x>
         <y>0</y>
         <width>51</width>
         <height>51</height>
        </rect>
       </property>
       <property name="text">
        <string>Sel</string>
       </property>
      </widget>
      <widget class="QComboBox" name="comboBox2SelectForm">
       <property name="geometry">
        <rect>
         <x>1</x>
         <y>51</y>
         <width>49</width>
         <height>20</height>
        </rect>
       </property>
      </widget>
     </widget>
     <widget class="QLabel" name="label2">
      <property name="geometry">
       <rect>
        <x>180</x>
        <y>80</y>
        <width>151</width>
        <height>22</height>
       </rect>
      </property>
      <property name="text">
       <string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p align=&quot;center&quot;&gt;Изображение&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
      </property>
     </widget>
     <widget class="QGroupBox" name="groupBox4">
      <property name="geometry">
       <rect>
        <x>240</x>
        <y>10</y>
        <width>111</width>
        <height>63</height>
       </rect>
      </property>
      <property name="title">
       <string/>
      </property>
      <widget class="QToolButton" name="toolButton1Crop">
       <property name="geometry">
        <rect>
         <x>0</x>
         <y>0</y>
         <width>111</width>
         <height>22</height>
        </rect>
       </property>
       <property name="text">
        <string>Обрезать</string>
       </property>
      </widget>
      <widget class="QToolButton" name="toolButton2ChangeSize">
       <property name="geometry">
        <rect>
         <x>0</x>
         <y>21</y>
         <width>111</width>
         <height>22</height>
        </rect>
       </property>
       <property name="text">
        <string>Изменить размер</string>
       </property>
      </widget>
      <widget class="QComboBox" name="comboBox3Rotate">
       <property name="geometry">
        <rect>
         <x>1</x>
         <y>43</y>
         <width>109</width>
         <height>20</height>
        </rect>
       </property>
      </widget>
     </widget>
     <widget class="Line" name="linev2">
      <property name="geometry">
       <rect>
        <x>360</x>
        <y>0</y>
        <width>3</width>
        <height>101</height>
       </rect>
      </property>
      <property name="orientation">
       <enum>Qt::Vertical</enum>
      </property>
     </widget>
     <widget class="QWidget" name="gridLayoutWidget">
      <property name="geometry">
       <rect>
        <x>370</x>
        <y>10</y>
        <width>97</width>
        <height>61</height>
       </rect>
      </property>
      <layout class="QGridLayout" name="gridLayout">
       <item row="0" column="2">
        <widget class="QToolButton" name="toolButton3Text">
         <property name="text">
          <string>...</string>
         </property>
        </widget>
       </item>
       <item row="0" column="1">
        <widget class="QToolButton" name="toolButton2Fill">
         <property name="text">
          <string>...</string>
         </property>
        </widget>
       </item>
       <item row="0" column="0">
        <widget class="QToolButton" name="toolButton1Pencil">
         <property name="text">
          <string>...</string>
         </property>
        </widget>
       </item>
       <item row="1" column="0">
        <widget class="QToolButton" name="toolButton4Erase">
         <property name="text">
          <string>...</string>
         </property>
        </widget>
       </item>
       <item row="1" column="1">
        <widget class="QToolButton" name="toolButton5Pipet">
         <property name="text">
          <string>...</string>
         </property>
        </widget>
       </item>
       <item row="1" column="2">
        <widget class="QToolButton" name="toolButton6Scale">
         <property name="text">
          <string>...</string>
         </property>
        </widget>
       </item>
      </layout>
     </widget>
     <widget class="QLabel" name="label3">
      <property name="geometry">
       <rect>
        <x>360</x>
        <y>80</y>
        <width>121</width>
        <height>22</height>
       </rect>
      </property>
      <property name="text">
       <string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p align=&quot;center&quot;&gt;Инструменты&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
      </property>
     </widget>
     <widget class="Line" name="linev3">
      <property name="geometry">
       <rect>
        <x>480</x>
        <y>0</y>
        <width>3</width>
        <height>101</height>
       </rect>
      </property>
      <property name="orientation">
       <enum>Qt::Vertical</enum>
      </property>
     </widget>
     <widget class="QToolButton" name="toolButton3Return">
      <property name="geometry">
       <rect>
        <x>590</x>
        <y>10</y>
        <width>51</width>
        <height>51</height>
       </rect>
      </property>
      <property name="text">
       <string>100%</string>
      </property>
     </widget>
     <widget class="QToolButton" name="toolButton1Zoom">
      <property name="geometry">
       <rect>
        <x>490</x>
        <y>10</y>
        <width>51</width>
        <height>51</height>
       </rect>
      </property>
      <property name="text">
       <string>+</string>
      </property>
     </widget>
     <widget class="QToolButton" name="toolButton2Zoom">
      <property name="geometry">
       <rect>
        <x>540</x>
        <y>10</y>
        <width>51</width>
        <height>51</height>
       </rect>
      </property>
      <property name="text">
       <string>-</string>
      </property>
     </widget>
     <widget class="QLabel" name="label4">
      <property name="geometry">
       <rect>
        <x>500</x>
        <y>80</y>
        <width>131</width>
        <height>22</height>
       </rect>
      </property>
      <property name="text">
       <string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p align=&quot;center&quot;&gt;Масштаб&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
      </property>
     </widget>
     <widget class="Line" name="linev4">
      <property name="geometry">
       <rect>
        <x>650</x>
        <y>0</y>
        <width>3</width>
        <height>101</height>
       </rect>
      </property>
      <property name="orientation">
       <enum>Qt::Vertical</enum>
      </property>
     </widget>
     <widget class="QLabel" name="labelSelectSize">
      <property name="geometry">
       <rect>
        <x>650</x>
        <y>30</y>
        <width>371</width>
        <height>21</height>
       </rect>
      </property>
      <property name="text">
       <string/>
      </property>
     </widget>
     <widget class="QLabel" name="labelSize">
      <property name="geometry">
       <rect>
        <x>650</x>
        <y>50</y>
        <width>371</width>
        <height>21</height>
       </rect>
      </property>
      <property name="text">
       <string/>
      </property>
     </widget>
     <widget class="QLabel" name="label6">
      <property name="geometry">
       <rect>
        <x>650</x>
        <y>80</y>
        <width>371</width>
        <height>22</height>
       </rect>
      </property>
      <property name="text">
       <string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p align=&quot;center&quot;&gt;Информация&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
      </property>
     </widget>
     <widget class="QLabel" name="labelCoords">
      <property name="geometry">
       <rect>
        <x>650</x>
        <y>10</y>
        <width>371</width>
        <height>21</height>
       </rect>
      </property>
      <property name="text">
       <string/>
      </property>
     </widget>
     <widget class="Line" name="linev5">
      <property name="geometry">
       <rect>
        <x>1020</x>
        <y>0</y>
        <width>3</width>
        <height>101</height>
       </rect>
      </property>
      <property name="orientation">
       <enum>Qt::Vertical</enum>
      </property>
     </widget>
     <widget class="QToolButton" name="toolButton4Paint">
      <property name="geometry">
       <rect>
        <x>1030</x>
        <y>10</y>
        <width>51</width>
        <height>51</height>
       </rect>
      </property>
      <property name="text">
       <string>Pain</string>
      </property>
     </widget>
     <widget class="QSpinBox" name="spinBoxWight">
      <property name="geometry">
       <rect>
        <x>1090</x>
        <y>10</y>
        <width>121</width>
        <height>22</height>
       </rect>
      </property>
     </widget>
     <widget class="QPushButton" name="pushButtonColorChose">
      <property name="geometry">
       <rect>
        <x>1090</x>
        <y>40</y>
        <width>121</width>
        <height>21</height>
       </rect>
      </property>
      <property name="text">
       <string>ChoseColor</string>
      </property>
     </widget>
     <widget class="QLabel" name="label7">
      <property name="geometry">
       <rect>
        <x>1020</x>
        <y>80</y>
        <width>201</width>
        <height>22</height>
       </rect>
      </property>
      <property name="text">
       <string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p align=&quot;center&quot;&gt;Кисть&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
      </property>
     </widget>
     <widget class="Line" name="linev7">
      <property name="geometry">
       <rect>
        <x>1220</x>
        <y>0</y>
        <width>3</width>
        <height>101</height>
       </rect>
      </property>
      <property name="orientation">
       <enum>Qt::Vertical</enum>
      </property>
     </widget>
     <widget class="QLabel" name="label8">
      <property name="geometry">
       <rect>
        <x>1220</x>
        <y>80</y>
        <width>231</width>
        <height>22</height>
       </rect>
      </property>
      <property name="text">
       <string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p align=&quot;center&quot;&gt;Фигуры&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
      </property>
     </widget>
     <widget class="QComboBox" name="comboBox">
      <property name="geometry">
       <rect>
        <x>1230</x>
        <y>10</y>
        <width>111</width>
        <height>31</height>
       </rect>
      </property>
     </widget>
     <widget class="QGroupBox" name="groupBox5">
      <property name="geometry">
       <rect>
        <x>1350</x>
        <y>10</y>
        <width>91</width>
        <height>42</height>
       </rect>
      </property>
      <property name="title">
       <string/>
      </property>
      <widget class="QToolButton" name="toolButton1ShapeOutline">
       <property name="geometry">
        <rect>
         <x>0</x>
         <y>0</y>
         <width>91</width>
         <height>22</height>
        </rect>
       </property>
       <property name="text">
        <string>Контур</string>
       </property>
      </widget>
      <widget class="QToolButton" name="toolButton2ShapeFill">
       <property name="geometry">
        <rect>
         <x>0</x>
         <y>20</y>
         <width>91</width>
         <height>22</height>
        </rect>
       </property>
       <property name="text">
        <string>Заливка</string>
       </property>
      </widget>
     </widget>
     <widget class="Line" name="linev8">
      <property name="geometry">
       <rect>
        <x>1450</x>
        <y>0</y>
        <width>3</width>
        <height>101</height>
       </rect>
      </property>
      <property name="orientation">
       <enum>Qt::Vertical</enum>
      </property>
     </widget>
    </widget>
   </widget>
   <widget class="Line" name="lineh1">
    <property name="geometry">
     <rect>
      <x>0</x>
      <y>24</y>
      <width>1920</width>
      <height>3</height>
     </rect>
    </property>
    <property name="orientation">
     <enum>Qt::Horizontal</enum>
    </property>
   </widget>
   <widget class="Line" name="lineh2">
    <property name="geometry">
     <rect>
      <x>0</x>
      <y>128</y>
      <width>1921</width>
      <height>3</height>
     </rect>
    </property>
    <property name="orientation">
     <enum>Qt::Horizontal</enum>
    </property>
   </widget>
   <widget class="QLabel" name="labelImage">
    <property name="geometry">
     <rect>
      <x>0</x>
      <y>131</y>
      <width>10</width>
      <height>10</height>
     </rect>
    </property>
    <property name="text">
     <string>Image</string>
    </property>
   </widget>
  </widget>
  <widget class="QMenuBar" name="menubar">
   <property name="geometry">
    <rect>
     <x>0</x>
     <y>0</y>
     <width>1925</width>
     <height>26</height>
    </rect>
   </property>
  </widget>
  <widget class="QStatusBar" name="statusbar"/>
 </widget>
 <resources/>
 <connections/>
</ui>````

1 ответ 1

1

Чтобы получить реальную ошибку - запустите ваше приложение в терминале/консоли/CMD.

Sorry, я не стал разбираться в вашем коде, но я вам предложу, как по мне хороший, вариант рисования мышью на изображении. Проверьте.

import sys
from PyQt5.Qt import *


class GraphicsScene(QGraphicsScene):
    def __init__(self, parent=None):
        super().__init__(parent)
        self._color_background = QColor("#393939")
        self.empty = True
        
        self.mainImage = QGraphicsPixmapItem()
        self.mainImage.setTransformationMode(Qt.SmoothTransformation)
        self.setBackgroundBrush(self._color_background)
      
        self.drawingGroup = self.createItemGroup([])
        blur = QGraphicsBlurEffect(blurRadius=1)
        self.drawingGroup.setGraphicsEffect(blur)
        self.drawingGroup.setZValue(100)

    def setImage(self, pixmap=None):
        if pixmap and not pixmap.isNull():
            self.empty = False
            self.mainImage.setPixmap(pixmap)
        else:
            self.empty = True
            self.mainImage.setPixmap(QPixmap())
        self.addItem(self.mainImage)

    def drawCircle(self, x, y, brushSize, pen, brush):
        item = QGraphicsEllipseItem(
            round(x), round(y), 
            brushSize, brushSize, 
            self.drawingGroup
        )
        item.setPen(pen)
        item.setBrush(brush)

    def drawLine(self, start_x, start_y, x, y, pen):
        item = QGraphicsLineItem(
            round(start_x), round(start_y), 
            round(x), round(y), 
            self.drawingGroup
        )
        item.setPen(pen)


class GraphicsView(QGraphicsView):
    def __init__(self, grScene, parent = None):
        super().__init__(parent)
        self.empty = True
        self.drawingMode = True
        self.brushSize = 5 
        
        self.brushColor = Qt.black
        self.lastPoint = QPoint()
        self.brush_line_pen = QPen(self.brushColor, self.brushSize, 
                                   Qt.SolidLine, Qt.RoundCap)

        self.grScene = grScene
        self.initUI()
        self.setScene(self.grScene)

        self.setDragMode(QGraphicsView.RubberBandDrag)
        self._isPanning = False
        self._mousePressed = False

        #zoom settings
        self.zoomInFactor = 1.25
        self.zoomOutFactor = 0.8
        self.zoomClamp = False
        self.zoom = 10
        self.zoomStep = 1
        self.zoomRange = [0, 20]
        if self.drawingMode:
            self.brush = self.grScene.addEllipse(
                0, 0, 
                self.brushSize, 
                self.brushSize, 
                QPen(Qt.NoPen), 
                self.brushColor
            )
            self.brush.setFlag(QGraphicsItem.ItemIsMovable)
            self.brush.setZValue(100)

    def initUI(self):
        self.setRenderHints(
            QPainter.Antialiasing | 
            QPainter.HighQualityAntialiasing | 
            QPainter.TextAntialiasing | 
            QPainter.SmoothPixmapTransform
        )
        self.setViewportUpdateMode(QGraphicsView.FullViewportUpdate)

    def setMainImage(self, pixmapItem):
        self.grScene.setImage(pixmapItem)

    def mousePressEvent(self,  event):
        if self.drawingMode and (event.button() == Qt.LeftButton):
            x = self.mapToScene(event.pos()).x()
            y = self.mapToScene(event.pos()).y()
            self.grScene.drawCircle(
                x - self.brushSize / 2, 
                y - self.brushSize / 2, 
                self.brushSize, 
                QPen(Qt.NoPen), 
                self.brushColor
            )
            self.lastPoint = self.mapToScene(event.pos())
        elif event.button() == Qt.LeftButton:
            self._mousePressed = True
            if self._isPanning:
                self.setCursor(Qt.ClosedHandCursor)
                self._dragPos = event.pos()
                event.accept()
            else:
                super(GraphicsView, self).mousePressEvent(event)

    def mouseMoveEvent(self, event):
        if self.drawingMode:
            x = self.mapToScene(event.pos()).x()
            y = self.mapToScene(event.pos()).y()
            self.brush.setPos(x - self.brushSize / 2, y - self.brushSize / 2)
            
        if (event.buttons() & Qt.LeftButton) & self.drawingMode:
            scenePos = QPointF(self.mapToScene(event.pos()).toPoint())
            self.grScene.drawLine(
                self.lastPoint.x(), self.lastPoint.y(), 
                scenePos.x(), scenePos.y(),
                self.brush_line_pen)
            self.lastPoint = scenePos
        elif self._mousePressed and self._isPanning:
            newPos = event.pos()
            diff = newPos - self._dragPos
            self._dragPos = newPos
            self.horizontalScrollBar().setValue(
                self.horizontalScrollBar().value() - diff.x())
            self.verticalScrollBar().setValue(
                self.verticalScrollBar().value() - diff.y())
            event.accept()
        else:
            super(GraphicsView, self).mouseMoveEvent(event)

    def mouseReleaseEvent(self, event):
        if event.buttons() == Qt.LeftButton:
            self._isPanning = False
            self.setCursor(Qt.ArrowCursor) 
            self._mousePressed = False  
        super(GraphicsView, self).mouseReleaseEvent(event)
   
    def wheelEvent(self, event):
        if event.angleDelta().y() > 0:
            step = self.zoomStep
            fact = self.zoomInFactor
        else:
            step = -self.zoomStep
            fact = self.zoomOutFactor
        zoom = max(self.zoomRange[0], min(self.zoom + step, self.zoomRange[1]))
        if zoom != self.zoom:
            self.zoom = zoom
            self.scale(fact, fact)        


class MainWindow(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.initUI()

    def initUI(self):
        self.grScene = GraphicsScene()
        self.view = GraphicsView(self.grScene, self)
        
        self.layout = QVBoxLayout(self)
        self.layout.setContentsMargins(0, 0, 0, 0)
        self.layout.addWidget(self.view)
     
        gl = QOpenGLWidget()
        gl.setMouseTracking(True)
        format = QSurfaceFormat()
        format.setSamples(4)
        gl.setFormat(format)
        self.view.setViewport(gl)
        
        self.loadImage()

    def loadImage(self):
        self.view.setMainImage(QPixmap('panda.jpg')) 


if __name__ == "__main__":
    app = QApplication(sys.argv)
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())

введите сюда описание изображения

введите сюда описание изображения


panda.jpg

введите сюда описание изображения

1
  • @AXAXAXAX что не так?
    – S. Nick
    Commented 13 дек. 2022 в 7:05

Ваш ответ

Нажимая «Отправить ответ», вы соглашаетесь с условиями пользования и подтверждаете, что прочитали политику конфиденциальности.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.