PyQt5 固定窗口大小

Ale*_*lex 3 python pyqt qt-designer pyqt5

我正在尝试将我的窗口 / QDialog 设置为不可调整大小。

我找到了下面的例子 self.setFixedSize(self.size())

我不确定如何实现这一点。我可以将它放在从 Qt Designer 生成的 .py 文件中或明确使用:

QtWidgets.QDialog().setFixedSize(self.size())
Run Code Online (Sandbox Code Playgroud)

没有错误,但它不起作用。谢谢。

Дми*_*нко 8

分别加载您的 UI 之后(如果您使用 .ui 文件)或在您的窗口的init () 中。应该是这样的:

class MyDialog(QtWidgets.QDialog):

    def __init__(self):
        super(MyDialog, self).__init__()
        self.setFixedSize(640, 480)
Run Code Online (Sandbox Code Playgroud)

让我知道这是否适合您。

编辑:这是应该如何重新格式化提供的代码才能工作。

from PyQt5 import QtWidgets 


# It is considered a good tone to name classes in CamelCase.
class MyFirstGUI(QtWidgets.QDialog): 

    def __init__(self):
        # Initializing QDialog and locking the size at a certain value
        super(MyFirstGUI, self).__init__()
        self.setFixedSize(411, 247)

        # Defining our widgets and main layout
        self.layout = QtWidgets.QVBoxLayout(self)
        self.label = QtWidgets.QLabel("Hello, world!", self)
        self.buttonBox = QtWidgets.QDialogButtonBox(self) 
        self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel | QtWidgets.QDialogButtonBox.Ok)

        # Appending our widgets to the layout
        self.layout.addWidget(self.label)
        self.layout.addWidget(self.buttonBox)

        # Connecting our 'OK' and 'Cancel' buttons to the corresponding return codes
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    gui = MyFirstGUI()
    gui.show()
    sys.exit(app.exec_())
Run Code Online (Sandbox Code Playgroud)