Question

I have a gui in ui_main.py file (designed in Qt Designer). I load it in my main *.py file in this way:

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:

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:

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. How can I resize my main window without editing a gui file?

Was it helpful?

Solution

The ui module created by pyuic (via Qt Designer) is just a simple helper class with a couple of initialization methods.

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. This ensures that everything created in Qt Designer is accessible from the top-level widget.

So your MyForm subclass passes self (an instance of QMainWindow) to setupUi, which then becomes the MainWindow variable you see in your ui file.

This means you can resize your main window by simply doing:

self.resize(300, 300)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top