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.
I like to display image at the center of label.
How can I do that?
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.
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.
I like to display image at the center of label.
How can I do that?
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.