Plot image at center of label in PyQT

Question:

QGridLayout is used to place QLabel.
Then cv2 images are displayed as follows.

frame = self.dequeList[cam.camID].popleft()
img = QtGui.QImage(frame, frame.shape[1], frame.shape[0], QtGui.QImage.Format_RGB888).rgbSwapped()
pix = QtGui.QPixmap.fromImage(img)
self.videoList[f"video_{cam.camID}"].setPixmap(pix)  

Now display start from 0,0 coordinates as below.
enter image description here
I like to display image at the center of label.
How can I do that?

Asked By: batuman

||

Answers:

To plot the image at the center of the QLabel, you can add the following line after creating the QPixmap object:

self.videoList[f"video_{cam.camID}"].setAlignment(QtCore.Qt.AlignCenter)

This sets the alignment of the label to Qt.AlignCenter, which centers the image in the label.

So the modified code would look like this:

from PyQt5 import QtGui, QtCore

frame = self.dequeList[cam.camID].popleft()
img = QtGui.QImage(frame, frame.shape[1], frame.shape[0], QtGui.QImage.Format_RGB888).rgbSwapped()
pix = QtGui.QPixmap.fromImage(img)
self.videoList[f"video_{cam.camID}"].setPixmap(pix)
self.videoList[f"video_{cam.camID}"].setAlignment(QtCore.Qt.AlignCenter)

Note : you need to import the QtCore module from PyQt5 to use the Qt.AlignCenter constant.

Answered By: debugger
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.