如何在PyQt4的控件上显示图片?
我想在我的表单上用PyQt4显示一张图片。
这是我的代码:
import sys
from PyQt4 import QtGui, QtCore
class myWindow(QtGui.QWidget):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
#The setGeometry method is used to position the control.
#Order: X, Y position - Width, Height of control.
self.resize(500,350)
self.center()
self.setWindowTitle("Sergio's QT Application.")
self.setWindowIcon(QtGui.QIcon('menuScreenFolderShadow.png'))
self.setToolTip('<i>Welcome</i> to the <b>first</b> app ever!')
QtGui.QToolTip.setFont(QtGui.QFont('Helvetica', 12))
self.txtFirstName = QtGui.QLineEdit('', self)
self.txtFirstName.setGeometry(35, 35, 150, 20)
self.txtLastName = QtGui.QLineEdit('', self)
self.txtLastName.setGeometry(35, 60, 150, 20)
self.pictureA = QtGui.QIcon("C:\Users\Sergio.Tapia\Downloads\Palm.png")
self.pictureA.setGeometry(128,128, 200, 200)
btnSubmit = QtGui.QPushButton('Say hello.', self)
btnSubmit.setGeometry(340, 250, 150, 35)
self.connect(btnSubmit, QtCore.SIGNAL("clicked()"), self.clicked)
btnQuit = QtGui.QPushButton('Exit Application', self)
btnQuit.setGeometry(340, 300, 150, 35)
self.connect(btnQuit, QtCore.SIGNAL('clicked()'),
QtGui.qApp, QtCore.SLOT('quit()'))
def clicked(self):
QtGui.QMessageBox.about(self, "Just dropped by to say hi!", "Welcome to this tutorial %s %s!" % (
self.txtFirstName.text(), self.txtLastName.text()))
def center(self):
screen = QtGui.QDesktopWidget().screenGeometry()
size = self.geometry()
self.move((screen.width()-size.width())/2, (screen.height()-size.height())/2)
app = QtGui.QApplication(sys.argv)
mainForm = myWindow()
mainForm.show()
sys.exit(app.exec_())
但是它提示我:
追踪信息(最近的调用在最前面):
文件 "C:\Users\Sergio.Tapia\Documents\NetBeansProjects\PyQTTests\src\pyqttests.py", 第47行,在 mainForm = myWindow() 文件 "C:\Users\Sergio.Tapia\Documents\NetBeansProjects\PyQTTests\src\pyqttests.py", 第25行,在 init self.pictureA.setGeometry(128,128, 200, 200) 属性错误:'QIcon' 对象没有属性'setGeometry'
如果我去掉那行setGeometry,应用程序可以启动,但图片却没有显示出来。谢谢大家的帮助!
1 个回答
1
有很多方法可以做到这一点,比如使用 QPixmap
这个类。我建议你去看看 PyQt 提供的示例。比如,examples\animation\appchooser\
,或者 examples\widgets\icons\
这些示例。