DrawLine within Qlabel in PyQt5

52 views Asked by At

I use Qt Designer to insert an image into the Qlabel as shown below. QT Designer image Then I want to draw a red cross on that image. For testing, I use the code below. When running the program, I can draw the cross at the desired position.

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)
        #!Load the UI Page
        uic.loadUi('myGUI.ui', self)
        # Init cross
        self.init_cross()
    def init_cross(self):
        #! Set the target image
        self.pixmap = self.label.pixmap()
        self.painter = QtGui.QPainter(self.pixmap)
        #! set colour and width of line
        self.painter.setPen(QtGui.QPen(QtGui.QColor('red'), 5))
        #! Draw the cross
        self.painter.drawLine(550, 550, 550 + CROSS_SIZE, 550 + CROSS_SIZE)
        self.painter.drawLine(550, 550 + CROSS_SIZE, 550 + CROSS_SIZE, 550)
        self.label.update()
        #self.label.setPixmap(pixmap)

However, I want to be able to use the draw_cross() function to draw after calculating the coordinates. But after calling the draw_cross() function, no cross is drawn. Please help me.

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)
        #!Load the UI Page
        uic.loadUi('myGUI.ui', self)
        # Init cross
        self.init_cross()

    def init_cross(self):
        #! Set the target image
        self.pixmap = self.label.pixmap()
        self.painter = QtGui.QPainter(self.pixmap)
        #! set colour and width of line
        self.painter.setPen(QtGui.QPen(QtGui.QColor('red'), 5))
        
    def draw_cross(self): 
        #! draw cross
        self.painter.drawLine(100, 100, 110 + CROSS_SIZE, 110 + CROSS_SIZE)
        self.painter.drawLine(100, 100 + CROSS_SIZE, 110 + CROSS_SIZE, 110)
        self.label.setPixmap(self.pixmap)
    
    def some_calculation(self): 
        self.draw_cross()

i tried different ways but still no success, self.pixmap and self.painter are both initialized correctly

Update: After rewriting the code according to @musicamante's (thanks again for your comment) suggestions, it seems like my code still doesn't work. Any suggestions?

def init_cross(self):
        #! Set the target image
        self.pixmap = self.label.pixmap()
        
 def draw_cross(self): 
        #! draw cross
        self.painter = QtGui.QPainter(self.pixmap)
        self.painter.setPen(QtGui.QPen(QtGui.QColor('red'), 5))
        self.painter.drawLine(100, 100, 110 + CROSS_SIZE, 110 + CROSS_SIZE)
        self.painter.drawLine(100, 100 + CROSS_SIZE, 110 + CROSS_SIZE, 110)
        self.painter.end()
        self.label.setPixmap(self.pixmap)
0

There are 0 answers