Reputation: 59594
I am loading a QMainWIndow base from a *.ui file. Also, i have a custom widget i want to place somewhere on the form. Currently i put in the .ui file an empty QVBoxLayout
named placeholder
, and in the QMainWindow subclass do self.placeholder.addWidget(my_custom_widget)
The only thing i don't like in this approach is that the empty layout does not have its own size. I can have a layout with one cell and with a dummy widget (QLabel
for example) with the size i want, and replace this widget and then add my custom widget, but the method seems too much for me.
What is your approach for such a task?
I am using Python (PyQt4)
Upvotes: 17
Views: 11305
Reputation:
Here is an easy little tutorial on how to promote a widget:
QWidget
in this case.MyWidget
MyWidget
is placed. Promote
. You are done promoting. QWidget
, it's MyWidget
instead.In the file at /path/to/MyWidget.py
I have a class named MyWidget
, and the content is something like this:
#!/usr/bin/env python
#-*- coding:utf-8 -*-
from PyQt4 import QtGui
class MyWidget(QtGui.QWidget):
def __init__(self, parent=None):
super(MyWidget, self).__init__(parent)
self.labelHello = QtGui.QLabel(self)
self.labelHello.setText("This is My Widget")
self.layout = QtGui.QHBoxLayout(self)
self.layout.addWidget(self.labelHello)
Upvotes: 33
Reputation: 59594
Well, not having a better solution for now, i ended up with a QVBoxLayout with one cell with a spacer in it:
FormClass, BaseClass = uic.loadUiType('main_window.ui')
assert BaseClass is QtGui.QMainWindow
class MainWindow(QtGui.QMainWindow, FormClass):
def __init__(self):
super().__init__()
# uic adds a function to our class called setupUi
# calling this creates all the widgets from the .ui file
self.setupUi(self)
# my custom widget
self.web_view = WebView(self, WebPage(self, self.print_to_console))
# replace placeholder with our widget
self.placeholder_layout.takeAt(0) # remove placeholder spacer
# and replace it with our widget
self.placeholder_layout.addWidget(self.web_view)
Upvotes: 3
Reputation: 12321
You should place a QWidget
in the QtDesigner
and then promote it to your custom widget. For more details check this link : http://doc.qt.digia.com/qt/designer-using-custom-widgets.html
Another option would be to create a QtDesigner plugin for your widget, but this would be useful only if you need to place in into multiple uis.
Upvotes: 4