How to keep Push Buttons constant in relative to c

2019-07-26 00:35发布

问题:

I have an image as my label in a PyQt4 Program. This program also contains some push buttons. Now, when I maximize my window, though the label gets expanded but the push button retain their place. I want that the push buttons should maintain their relative position with respect to the label, even when maximized.

My code is as follows:

class Ui_MainWindow(object):
   def setupUi(self, MainWindow):

       self.centralwidget = QtGui.QWidget(MainWindow)
       MainWindow.setCentralWidget(self.centralwidget)
       lay = QtGui.QVBoxLayout(self.centralwidget)
       self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
       self.label = QtGui.QLabel(self.centralwidget)
       self.label.setText(_fromUtf8(""))
       self.label.setPixmap(QtGui.QPixmap(_fromUtf8("Capture.PNG")))
       self.label.setObjectName(_fromUtf8("label"))
       self.label.setScaledContents(True)
       lay.addWidget(self.label)
       self.Langdon = QtGui.QPushButton(self.centralwidget)
       self.Langdon.setGeometry(QtCore.QRect(290, 90, 75, 23))
       self.Langdon.setObjectName(_fromUtf8("Langdon"))     
       self.ChainLakes = QtGui.QPushButton(self.centralwidget)
       self.ChainLakes.setGeometry(QtCore.QRect(50, 290, 85, 23))
       self.ChainLakes.setObjectName(_fromUtf8("ChainLakes"))

   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_())

How shall I modify my code??

回答1:

You're using absolute positioning for the buttons, but relative for the label (because it is in the layout). Since the buttons are positioned absolutely, you're responsible for moving them around yourself whenever the container size (your main window or central widget) changes. OTOH if you position them using a layout, the layout then moves them around as needed (as with the label).

I highly recommend you find a layout-based solution which would suit your needs (they're very flexible but can sometimes take a bit of fiddling). Barring that, you'll need to subclass the container (your centralWidget QWidget) and re-implement the QWidget::resizeEvent() handler. Inside that handler you would move the absolutely positioned elements (the buttons) to a new position based on current size of the container and current size/position of the label.

I'm not handy enough with PyQt to give a concrete example (sorry), but I did provide a similar answer to a C++ question which may be useful: QPushButton alignment on top another widget