問題描述
我有一個圖像作為我在 PyQt4 程序中的標簽.該程序還包含一些按鈕.現在,當我最大化我的窗口時,雖然標簽得到擴展,但按鈕保留了它們的位置.我希望按鈕應該保持它們相對于標簽的相對位置,即使在最大化時也是如此.
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.
我的代碼如下:
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??
推薦答案
您對按鈕使用絕對定位,而對標簽使用相對定位(因為它在布局中).由于按鈕是絕對定位的,因此只要容器大小(您的主窗口或中央小部件)發生變化,您就有責任在自己周圍移動它們.OTOH,如果您使用布局定位它們,則布局會根據需要移動它們(與標簽一樣).
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).
我強烈建議您找到一個適合您需求的基于布局的解決方案(它們非常靈活,但有時可能需要一些小技巧).除此之外,您需要子類化容器(您的 centralWidget
QWidget
)并重新實現 QWidget::resizeEvent()
處理程序.在該處理程序中,您將根據容器的當前大小和標簽的當前大小/位置將絕對定位的元素(按鈕)移動到新位置.
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.
我對 PyQt 不夠方便,無法給出具體示例(抱歉),但我確實為可能有用的 C++ 問題提供了類似的答案:QPushButton 在另一個小部件頂部對齊
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
這篇關于如何在 PyQt4 中相對于標簽大小的變化保持按鈕不變的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!