How to Add Widget after loading QtDesiger ui file?

Heads up! You've already completed this tutorial.

parkerlewis4047061 | 2021-02-06 01:34:46 UTC | #1

I'm following the post

And loading the ui works fine self.mainbox = uic.loadUi('mainwindow.ui', self)

But, how can add a button or label, to either the main window and/or my PlotWidget?
self.label = QtWidgets.QLabel()

For example, none of these work: self.mainbox.addWidget(self.label) self.mainbox.graphWidget().addWidget(self.label) self.mainbox.layout().addWidget(self.label)

How can I access either the main window's layout or my PlotWidget layout? Or Do I need instead to create a NEW layout using setCentralWidget or setLayout? vLayout = QVBoxLayout () vLayout.addWidget( loadUi( 'mainwindow.ui' ) )

martin | 2021-02-06 09:43:51 UTC | #2

Hi @parkerlewis4047061 welcome to the forum!

To add widgets you need to have a layout in place, and add the widget to that. In your example is mainbox a layout, or a widget? If you can post your ui file here, I can take a look at it.

If mainbox is a container QWidget you can set a layout on it using .setLayout() although this will replace any layout that is currently set (for example in your ui file).

You can also set a layout on a widget in Qt designer, and access that either by name or through the widget that has the layout assigned -- like in your final example self.mainbox.layout().addWidget(self.label) what error are you seeing when you do this?

The names of objects are defined in your ui file (editable within Qt Designer) -- if they're not accessible where you think they should be, check the objectName that is defined in designer to make sure it's correct.

Another option is to convert the ui file to Python (using pyuic5) -- you can then look in the resulting Python file to see how things are organised.

Over 10,000 developers have bought Create GUI Applications with Python & Qt!
Create GUI Applications with Python & Qt5
More info Get the book

Downloadable ebook (PDF, ePub) & Complete Source code

[[ discount.discount_pc ]]% OFF for the next [[ discount.duration ]] [[discount.description ]] with the code [[ discount.coupon_code ]]

Purchasing Power Parity

Developers in [[ country ]] get [[ discount.discount_pc ]]% OFF on all books & courses with code [[ discount.coupon_code ]]
Well done, you've finished this tutorial! Mark As Complete
[[ user.completed.length ]] completed [[ user.streak+1 ]] day streak

How to Add Widget after loading QtDesiger ui file? was written by Martin Fitzpatrick .

Martin Fitzpatrick has been developing Python/Qt apps for 8 years. Building desktop applications to make data-analysis tools more user-friendly, Python was the obvious choice. Starting with Tk, later moving to wxWidgets and finally adopting PyQt.

Interested in contributing to the site? Find out more.