【问题标题】:QLabel doesn't display pixmapQLabel 不显示像素图
【发布时间】:2014-10-13 09:28:50
【问题描述】:

我正在尝试在 QLabel 中显示 QPixmap,但标签为空。

这是我的代码:

#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys
from PyQt4 import QtGui

class Test(QtGui.QWidget):

    def __init__(self):
        super(Test, self).__init__()

        self.initUI()

    def initUI(self):      
        pixmap = QtGui.QPixmap("test.png")

        lbl = QtGui.QLabel(self)
        lbl.setPixmap(pixmap)

        self.move(300, 200)
        self.setWindowTitle('Test')
        self.show()        

app = QtGui.QApplication(sys.argv)
ex = Test()
sys.exit(app.exec_())

当我启动应用程序时,我只得到一个空窗口:

我使用 Linux 发行版 (Manjaro)。我用 Ubuntu 测试过,但我遇到了同样的问题。

我不明白出了什么问题,因为我成功地在QGraphicsSceneQIconQPushButton 中显示了其他QPixmaps

如何在我的标签中显示QPixmap

编辑:

这是另一个带有布局的版本,但不能解决问题:

#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys
from PyQt4 import QtGui

class Test(QtGui.QWidget):

    def __init__(self):
        super(Test, self).__init__()

        self.initUI()

    def initUI(self):      
        layout = QtGui.QVBoxLayout()
        pixmap = QtGui.QPixmap("test.png")

        lbl = QtGui.QLabel(self)
        lbl.setPixmap(pixmap)

        layout.addWidget(lbl)
        self.setLayout(layout)

        self.move(300, 200)
        self.setWindowTitle('test')
        self.show()        

app = QtGui.QApplication(sys.argv)
ex = Test()
sys.exit(app.exec_())

【问题讨论】:

  • 检查像素图加载是否正常。
  • 对我有用(两个版本) - 代码通常是正确的。您确定要从 .png 文件所在的同一目录启动脚本吗?如何启动脚本(从命令行/从 IDE)?
  • 是的,我在同一目录中启动了脚本。但我意识到,如果我使用绝对路径,它就可以工作。所以一定是路径问题。坦克你的帮助。
  • @arthropode 供您参考,这是我用于测试的确切代码:github.com/afester/StackOverflow/tree/master/Python/PyQtPixmap - 当我在命令上启动脚本时,python 脚本是问题中代码的精确副本PyQtPixmap 目录中的./v1.py 行,显示图像
  • 尝试用QtGui.QPixmap(":/images/test.png") 替换QtGui.QPixmap("test.png") - 当然,首先创建图像目录并将test.png 移到那里。

标签: python linux qt pyqt


【解决方案1】:

问题不在于路径 问题是从 VSC 执行程序时 如果您在 CMD 或 TERMINAL 中执行程序,程序运行并显示图像! 经测试!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-01
    相关资源
    最近更新 更多