Sikander Ahmad
Sikander Ahmad

Reputation: 45

Setting Position of Image in main Window, QPixmap

im using QPixmap to load image and set the position. Image loads in my main window but the position of image is not setting i used setPos but didn't happen anything.

from PyQt5 import QtGui
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import QApplication, QDialog, QVBoxLayout, QLabel
from PyQt5 import QtCore

import sys
from PyQt5.QtGui import QPixmap
class Window(QDialog):
    def __init__(self):
        super().__init__()
        self.title = "PyQt5 Adding Image To Label"
        self.top = 200
        self.left = 500
        self.width = 400
        self.height = 500
        self.InitWindow()

    def InitWindow(self):
        self.setWindowIcon(QtGui.QIcon("icon.png"))
        self.setWindowTitle(self.title)
        self.setStyleSheet("background-color:#202020")
        self.setGeometry(self.left, self.top, self.width, self.height)
        vbox = QVBoxLayout()
        labelImage = QLabel(self)

        pixmap = QPixmap("mario.png")
        pixmap=pixmap.scaled(50, 50, QtCore.Qt.KeepAspectRatio)
        #pixmap.setPos(100,60)

        labelImage.setPixmap(pixmap)
        vbox.addWidget(labelImage)
        self.setLayout(vbox)

        self.show()



App = QApplication(sys.argv)
window = Window()
sys.exit(App.exec_())

Upvotes: 0

Views: 4264

Answers (1)

eyllanesc
eyllanesc

Reputation: 243897

The following concepts must be clear:

  • QPixmap is not a visual element but a container for the bits that make up the image so they don't have any setPos() method (recommendation: check the Qt docs).

  • The visual element that shows the content of the QPixmap in your code is the QLabel so you must set the position to that widget, but in this case the OP is using layouts that aim to manage the geometry (position and size) so you should not use it if you want to set it manually.

def InitWindow(self):
    self.setWindowIcon(QtGui.QIcon("icon.png"))
    self.setWindowTitle(self.title)
    self.setStyleSheet("background-color:#202020")
    self.setGeometry(self.left, self.top, self.width, self.height)

    labelImage = QLabel(self)
    pixmap = QPixmap("mario.png")
    pixmap = pixmap.scaled(50, 50, QtCore.Qt.KeepAspectRatio)
    labelImage.setPixmap(pixmap)
    labelImage.move(100, 100)

    self.show()

Upvotes: 2

Related Questions