我遇到了以下代码来创建PyQT窗口。
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()
我想在这个窗口上插入/嵌入一个图像(比如说已知路径的image.jpg)。它应该优选地位于窗口的底部并且不应该消耗整个窗口。我怎么能这样做?
答案 0 :(得分:1)
我们可以使用QLabel来显示图像,因为它有一个setPixmap方法,如下所示
c
完整代码:
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()
截图:
底
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()
截图: