PyQt5:将按钮位置附加到窗口坐标上

问题描述 投票:0回答:1

因此,我正在尝试对PyQt5进行试验。我创建了一个带有两个QPushButtons的基本窗口。

from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow, QSizePolicy
import sys

class Okno(QMainWindow):
    def __init__(self):
        super(Okno, self).__init__()
        self.setGeometry(500, 500, 900, 500)  # window size setGeometry(xpos, ypos, w, h)
        # self.setFixedSize(900, 500) # fix window position
        self.setWindowTitle("My window")
        self.label = QtWidgets.QLabel(self)
        self.button1 = QtWidgets.QPushButton(self)
        self.button2 = QtWidgets.QPushButton(self)
        self.iniUI()

    # Buttons
    def iniUI(self):
        self.button1.setText("Open file")
        self.button1.move(75, 450)
        self.button1.setMinimumWidth(150)
        self.button1.clicked.connect(Button_events.open_file)  # add (connect) button event 

        self.button2.setText("Exit")
        self.button2.move(750, 450)
        self.button2.clicked.connect(exit)

# Button events
class Button_events(QMainWindow):
    def open_file(self):
        print("Open file")

# Main method
def window():
    app = QApplication(sys.argv)
    okno = Okno()
    okno.show()
    sys.exit(app.exec_())


window()

我已经通过绝对坐标设置了按钮的位置。调整My Window的大小时,按钮仅保留其绝对坐标。

如何将按钮的坐标附加到My Window,因此在缩放窗口时,按钮将在其中移动。

是否可以相对于最小My Window大小设置最小QPushButtons大小(当按钮不适合My Window时,不能将其调整得更小)?

这是我要实现的简单屏幕(原始按钮被切成两半,如果My Window变小,它们将消失:]

enter image description here

谢谢。

python pyqt5 window qpushbutton qmainwindow
1个回答
0
投票

我建议使用布局来处理所有小部件的位置和窗口的最小尺寸。使用QGridLayout,可以将按钮对准左下角和右下角。

from PyQt5 import QtWidgets, QtCore
from PyQt5.QtWidgets import QApplication, QMainWindow, QSizePolicy
import sys

class Okno(QMainWindow):
    def __init__(self):
        super(Okno, self).__init__()
        self.setGeometry(500, 500, 900, 500)
        self.setWindowTitle("My window")
        self.label = QtWidgets.QLabel()
        self.button1 = QtWidgets.QPushButton()
        self.button2 = QtWidgets.QPushButton()
        self.iniUI()

    # Buttons
    def iniUI(self):
        w = QtWidgets.QWidget()
        self.setCentralWidget(w)
        grid = QtWidgets.QGridLayout(w)

        self.button1.setText("Open file")
        self.button1.setMinimumWidth(150)
        self.button1.clicked.connect(self.open_file)
        self.button2.setText("Exit")
        self.button2.clicked.connect(self.close)

        grid.addWidget(self.button1, 0, 0, QtCore.Qt.AlignLeft | QtCore.Qt.AlignBottom)
        grid.addWidget(self.button2, 0, 1, QtCore.Qt.AlignRight | QtCore.Qt.AlignBottom)

    def open_file(self):
        print("Open file")


def window():
    app = QApplication(sys.argv)
    okno = Okno()
    okno.show()
    sys.exit(app.exec_())

window()
© www.soinside.com 2019 - 2024. All rights reserved.