PyQt4 中标签的自动调整大小

Auto Resize of Label in PyQt4

我在 PyQt4 中添加了一个包含图像的标签。此图像在未最大化时完全适合 window。我的目标是标签应该自动调整大小并完全适合 window 即使最大化。我的代码如下:

class Ui_MainWindow(object):
   def setupUi(self, MainWindow):
       MainWindow.setObjectName(_fromUtf8("MainWindow"))
       MainWindow.resize(1047, 600)
       self.centralwidget = QtGui.QWidget(MainWindow)
       self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
       self.label = QtGui.QLabel(self.centralwidget)
       self.label.setGeometry(QtCore.QRect(0, 0, 1081, 551))
       self.label.setText(_fromUtf8(""))
       self.label.setPixmap(QtGui.QPixmap(_fromUtf8("Capture.PNG")))
       self.label.setObjectName(_fromUtf8("label"))
   if __name__ == "__main__":
      import sys
      app = QtGui.QApplication(sys.argv)
      MainWindow = QtGui.QMainWindow()
      ui = Ui_MainWindow()
      ui.setupUi(MainWindow)
      MainWindow.show()
      sys.exit(app.exec_())

请告诉我如何修改我的代码?

您必须执行以下操作:

  • centralwidget 设置为 QMainWindowcentralWidget
  • 使用布局将 QLabel 放在 centralwidget 内。
  • 启用 QLabelScaledContents 属性。

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        self.centralwidget = QtGui.QWidget(MainWindow)
        MainWindow.setCentralWidget(self.centralwidget) # <--
        lay = QtGui.QVBoxLayout(self.centralwidget)
        self.label = QtGui.QLabel(self.centralwidget)
        self.label.setPixmap(QtGui.QPixmap("Capture.PNG"))
        self.label.setScaledContents(True) # <--
        lay.addWidget(self.label) # <--