简体   繁体   English

使用 Qt 在 Python 中调整主窗口大小

[英]Main Window resize in Python with Qt

I have a gui in ui_main.py file (designed in Qt Designer).我在ui_main.py文件中有一个 gui(在 Qt Designer 中设计)。 I load it in my main *.py file in this way:我以这种方式将它加载到我的主*.py文件中:

from PyQt4 import QtGui, QtCore
from ui_main import Ui_MainWindow
class MyForm(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
...

ui_main.py file: ui_main.py 文件:

from PyQt4 import QtCore, QtGui

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    _fromUtf8 = lambda s: s

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName(_fromUtf8("MainWindow"))
        MainWindow.resize(667, 559)

I need to resize my main window during application start.我需要在应用程序启动期间调整主窗口的大小。 My main problem is that I can't get access to Main window object.我的主要问题是我无法访问主窗口对象。

 self.ui.MainWindow.resize(300,300)
 AttributeError: 'Ui_MainWindow' object has no attribute 'MainWindow'

If I add to ui_main.py file:如果我添加到ui_main.py文件:

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        self.uiui = MainWindow

I can resize my main window with:我可以调整我的主窗口大小:

self.ui.uiui.resize(300,300) 

But I know that it's very bad to edit generated ui file.但我知道编辑生成的 ui 文件非常糟糕。 How can I resize my main window without editing a gui file?如何在不编辑 gui 文件的情况下调整主窗口的大小?

The ui module created by pyuic (via Qt Designer) is just a simple helper class with a couple of initialization methods.pyuic (通过 Qt Designer)创建的 ui 模块只是一个简单的辅助类,带有几个初始化方法。

Both methods take an instance of the top-level ui class from Qt Designer (usually a QMainWindow ), and then add the all the ui elements to that instance.这两种方法都从 Qt Designer 中获取一个顶级 ui 类的实例(通常是QMainWindow ),然后所有 ui 元素添加该实例中。 This ensures that everything created in Qt Designer is accessible from the top-level widget.这确保了在 Qt Designer 中创建的所有内容都可以从顶级小部件访问。

So your MyForm subclass passes self (an instance of QMainWindow ) to setupUi , which then becomes the MainWindow variable you see in your ui file.因此,您的MyForm子类将selfQMainWindow的一个实例)传递给setupUi ,然后它将成为您在 ui 文件中看到的MainWindow变量。

This means you can resize your main window by simply doing:这意味着您只需执行以下操作即可调整主窗口的大小:

self.resize(300, 300)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM