Replacing a widget at runtime

Here's the situation. I have a class that is derived from a QListView that adds some handy functionality, a custom widget if you like. I don't want to struggle with a designer to use my widget. I just want to use a simple QlistView in Designer (as a placeholder) and compile with pyuic4. At runtime, I want to replace this regular QListView with my own version.

How can you do this?

I was hoping that something like this in init would do the trick:

self.lstView1 = MyListView

      

But it is not...

+2


source to share


2 answers


The problem is that you are actually just replacing the object specified by lstView1, but not adding it to the widget. That is, when you instantiate an object, you just tell python to point to your new object using lstView1, but the actual UI is using the old pointer as it has already been added.

I am assuming you are using py4uci to convert ui files to python and you are setting up the gui like:

class ExambleUI(QtGUi.QDialog, UI_Example):
   def __init__(self, parent):
       QtGui.QDiialog.__init__(self, parent)
       self.setupUI(self)
       self.lstView1 = MyListView

      



Since the setupUi runs before the lstView value changes, you don't get a new widget. You just need to swap the lines:

class ExambleUI(QtGUi.QDialog, UI_Example):
   def __init__(self, parent):
       QtGui.QDiialog.__init__(self, parent)
       self.lstView1 = MyListView
       self.setupUI(self)

      

On the other hand, I recommend that you follow this tutorial and create and use your widget in the designer, it's easy and fast.

+2


source


Use the replace function QLayout:



ui->main_layout->replace(oldWidget, newWidget);

      

0


source







All Articles