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 https://www.pythonguis.com/tutorials/embed-pyqtgraph-custom-widgets-qt-app/

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!

To support developers in [[ countryRegion ]] I give a [[ localizedDiscount[couponCode] ]]% discount with the code [[ couponCode ]] — Enjoy!

For [[ activeDiscount.description ]] I'm giving a [[ activeDiscount.discount ]]% discount with the code [[ couponCode ]] — Enjoy!

Well done, you've finished this tutorial! Mark As Complete
[[ user.completed.length ]] completed [[ user.streak+1 ]] day streak