本文介绍了设置主窗口中图像的位置,QPixmap的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

im 使用 QPixmap 加载图像并设置位置.图像加载到我的主窗口中,但图像的位置没有设置我使用了 setPos 但没有发生任何事情.

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_())

推荐答案

以下概念一定要清楚:

  • QPixmap 不是视觉元素,而是构成图像的位的容器,因此它们没有任何 setPos() 方法(推荐:检查 Qt 文档).

在您的代码中显示 QPixmap 内容的视觉元素是 QLabel,因此您必须将位置设置为该小部件,但在这种情况下,OP 使用旨在管理几何图形(位置和size) 所以如果你想手动设置它,你不应该使用它.

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()

这篇关于设置主窗口中图像的位置,QPixmap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 14:35