【问题标题】:PyQt5 Fixed Window SizePyQt5 固定窗口大小
【发布时间】:2019-03-02 05:15:39
【问题描述】:

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

我找到了以下示例 self.setFixedSize(self.size())

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

QtWidgets.QDialog().setFixedSize(self.size())

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

【问题讨论】:

标签: python pyqt pyqt5 qt-designer


【解决方案1】:

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

class MyDialog(QtWidgets.QDialog):

    def __init__(self):
        super(MyDialog, self).__init__()
        self.setFixedSize(640, 480)

让我知道这是否适合你。

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

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

【讨论】:

  • 这里的诀窍是将固定大小的属性分配给正确的对象。 IIRC,当您使用 pyuic5 从 Designer 文件生成代码时,该类派生自对象,而不是您想要的窗口类型,因此导致不正确的行为。
  • 我明白了,谢谢。我仍然无法使用它,例如在默认的 .ui 到 .py 文件中。 from PyQt5 import QtCore, QtGui, QtWidgets class Ui_myfirstgui(object): def setupUi(self, myfirstgui): myfirstgui.setObjectName("myfirstgui") myfirstgui.resize(411, 247) self.buttonBox = QtWidgets.QDialogButtonBox(myfirstgui) self.buttonBox.setGeometry(QtCore.QRect(20, 210, 381, 32)) self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
  • 我明白为什么。 resize() 只为窗口设置一定的大小,它不会锁定用户以后调整它的大小。您的代码中没有调用 setupUi() 的入口点。 pyuic5 会生成可怕的代码,其中包含许多不必要/违反直觉的东西。不要在不返工的情况下使用它,并查看我的编辑以供参考。
  • 非常感谢。我也很感谢 cmets,肯定有助于为新的 PyQt 用户解决一些问题。
  • 另外,我可以理解您在不必要的代码方面的意思。例如。你的最后一部分有 pyuic 生成的 5 vs 7。
【解决方案2】:

exp:

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(700, 494)
        MainWindow.setFixedSize(300,300) :

MainWindow对象设置固定窗口

    self.height =300
    self.width =300
    self.top =50
    self.left =50

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-06
    • 2012-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-16
    相关资源
    最近更新 更多