PyQt - how to add separate UI widget to QMainWindow

linuxoid picture linuxoid · Jan 11, 2012 · Viewed 61.9k times · Source

I've only recently started programming and Python (PyQt) in particular. I have my main QMainWindow class. But I wanted to separate it from UI widgets, so that all windows stuff (menus, toolbars, common buttons) are in QMainWindow, but all program/UI specific widgets (pusgbuttons, comboboxes, images, checkboxes etc.) are in a separate QWidget class. But I'm not sure if I'm doing this right.

  1. I have a problem with layouts - something invisible is covering the menus so that they're not clickable by mouse, I think I'm not adding my UI widget to the main window correctly

Here's how I do it:

class MyMainWindow(QMainWindow):
    def __init__(self, parent = None):
        super(MyMainWindow, self).__init__(parent)

        self.main_widget = QWidget(self)
        ...
        self.form_widget = FormWidget(self) 
        #This is my UI widget

        self.main_layout = QVBoxLayout(self.main_widget)
        self.main_layout.sizeConstraint = QLayout.SetDefaultConstraint
        self.main_layout.addWidget(self.form_widget.main_widget) 
        #form_widget has its own main_widget where I put all other widgets onto

        self.main_widget.setLayout(self.main_layout)
        self.setCentralWidget(self.main_widget)
  1. I've seen other Python programs where applications are broken into a lot of small files of code (as I understand it, having everything in on main class is unreadable or unmanageable).

What's your suggestion about breaking code into small pieces? How's it better done? Or for UI it can all be in one big place? Should I break UI code/classes into separate file at all?

Thank you.

[SOLVED]

I found my mistake - I deleted the main_widget from the UI widget class (now all UI widgets are placed directly on the UI class widget itself) and only do this:

self.main_layout.addWidget(self.form_widget)

no more problems with menus

Answer

Jeff picture Jeff · Jan 11, 2012

Are you looking for something like this? I'm not really sure what your main_widget is

from PyQt4.QtCore import *
from PyQt4.QtGui  import *

import sys

class MyMainWindow(QMainWindow):

    def __init__(self, parent=None):

        super(MyMainWindow, self).__init__(parent)
        self.form_widget = FormWidget(self) 
        self.setCentralWidget(self.form_widget) 


class FormWidget(QWidget):

    def __init__(self, parent):        
        super(FormWidget, self).__init__(parent)
        self.layout = QVBoxLayout(self)

        self.button1 = QPushButton("Button 1")
        self.layout.addWidget(self.button1)

        self.button2 = QPushButton("Button 2")
        self.layout.addWidget(self.button2)

        self.setLayout(self.layout)

app = QApplication([])
foo = MyMainWindow()
foo.show()
sys.exit(app.exec_())