3

Here is the situation. I have a class which is derived from a QListView that adds some convenience functions, a custom widget if you like. I do not want to wrestle with the Designer to use my widget. I simply want to use a plain QlistView in the Designer (as a placeholder) and compile it with pyuic4. At runtime I want to replace that normal QListView with my own version.

How can you do this?

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

self.lstView1 = MyListView

but it doesn't...

4

2 回答 2

3

问题是您实际上只是替换了 lstView1 指向的对象,但没有将其添加到小部件中。也就是说,当您创建对象时,您只需告诉 python 使用 lstView1 指向您的新对象,但实际 UI 使用旧指针,因为它已经添加。

我将假设您已使用 py4uci 将 ui 文件转换为 python,并将 gui 设置为:

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

因为 setupUi 是在您更改 lstView 的值之前执行的,所以您不会获得新的小部件。你只需要换行:

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

另一方面,我建议您按照本教程在设计器中创建和使用您的小部件,它既简单又快捷。

于 2009-09-11T12:26:21.267 回答
1

使用 QLayout 替换功能:

ui->main_layout->replace(oldWidget, newWidget);
于 2017-03-09T05:27:13.463 回答