Reputation: 467
I came across the following code to create a PyQT window.
class PrettyWidget(QtGui.QWidget):
def __init__(self):
super(PrettyWidget, self).__init__()
self.initUI()
def initUI(self):
self.setGeometry(600,300,1000,600)
self.center()
self.setWindowTitle('Browser')
self.show()
def center(self):
qr = self.frameGeometry()
cp = QtGui.QDesktopWidget().availableGeometry().center()
qr.moveCenter(cp)
self.move(qr.topLeft())
def main():
app = QtGui.QApplication(sys.argv)
w = PrettyWidget()
app.exec_()
if __name__ == '__main__':
main()
I would like to insert/embed an image onto this window (say image.jpg with the path known). It should preferably be at the bottom of the window and should not consume the entirety of the window. How can I do that ?
Upvotes: 0
Views: 18114
Reputation: 243887
We can use QLabel to display the image since it has a setPixmap method, as I show below
lb = QtGui.QLabel(self)
pixmap = QtGui.QPixmap("{path/of/file}")
height_label = 100
lb.resize(self.width(), height_label)
lb.setPixmap(pixmap.scaled(lb.size(), QtCore.Qt.IgnoreAspectRatio))
self.show()
Complete code:
class PrettyWidget(QtGui.QWidget):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent=parent)
self.initUI()
def initUI(self):
self.resize(1000,600)
self.center()
self.setWindowTitle('Browser')
self.lb = QtGui.QLabel(self)
pixmap = QtGui.QPixmap("test.png")
height_of_label = 100
self.lb.resize(self.width(), height_of_label)
self.lb.setPixmap(pixmap.scaled(self.lb.size(), QtCore.Qt.IgnoreAspectRatio))
self.show()
def resizeEvent(self, event):
self.lb.resize(self.width(), self.lb.height())
self.lb.setPixmap(self.lb.pixmap().scaled(self.lb.size(), QtCore.Qt.IgnoreAspectRatio))
QtGui.QWidget.resizeEvent(self, event)
def center(self):
qr = self.frameGeometry()
cp = QtGui.QDesktopWidget().availableGeometry().center()
qr.moveCenter(cp)
self.move(qr.topLeft())
def main():
app = QtGui.QApplication(sys.argv)
w = PrettyWidget()
app.exec_()
if __name__ == '__main__':
main()
Screenshot:
Bottom:
def initUI(self):
self.resize(1000,600)
self.center()
self.setWindowTitle('Browser')
self.lb = QtGui.QLabel(self)
pixmap = QtGui.QPixmap("test.png")
height_of_label = 100
self.lb.resize(self.width(), height_of_label)
self.lb.move(0, self.height() -self.lb.height())
self.lb.setPixmap(pixmap.scaled(self.lb.size(), QtCore.Qt.IgnoreAspectRatio))
self.show()
def resizeEvent(self, event):
self.lb.resize(self.width(), self.lb.height())
self.lb.setPixmap(self.lb.pixmap().scaled(self.lb.size(), QtCore.Qt.IgnoreAspectRatio))
self.lb.move(0, self.height() -self.lb.height())
QtGui.QWidget.resizeEvent(self, event)
Screenshot:
Upvotes: 3