自定义小部件的占位符

时间:2013-01-23 13:26:09

标签: qt qt4 pyqt pyqt4 pyside

我正在从* .ui文件加载QMainWIndow基础。此外,我有一个自定义小部件,我想放在窗体上的某个地方。目前,我在.ui文件中添加了一个名为QVBoxLayout的空placeholder,并在QMainWindow子类中添加了self.placeholder.addWidget(my_custom_widget)

在这种方法中我唯一不喜欢的是空布局没有自己的大小。我可以使用一个单元格和一个虚拟小部件(例如QLabel)布局我想要的大小,并替换此小部件然后添加我的自定义小部件,但这个方法对我来说似乎太多了。

您完成此类任务的方法是什么?

我正在使用Python(PyQt4)

3 个答案:

答案 0 :(得分:26)

这是一个关于如何推广小部件的简单小教程:

  1. 右键单击要用作占位符的小部件,然后选择提升为...

    Image Promote

  2. 填写 Promoted Clases 弹出对话框字段:
    • 基类名称:在这种情况下为QWidget
    • 推荐的班级名称:您用于定义要为其创建占位符的窗口小部件的类名称,此处为MyWidget
    • 标头文件 /path/to/MyWidget.py 是放置MyWidget的文件的路径。 Image Path
  3. 点击添加后,会创建并显示该类,选择该类并单击Promote。你完成了推广。 Image Add
  4. 您应该在对象检查器面板中看到以下内容,该类的名称不再是QWidget,而是MyWidget
    Image Promoted

  5. /path/to/MyWidget.py的文件中,我有一个名为MyWidget的类,内容是这样的:

    #!/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)
    

答案 1 :(得分:3)

您应该在QWidget中放置QtDesigner,然后将其提升为自定义小部件。有关详细信息,请点击此链接:http://doc.qt.digia.com/qt/designer-using-custom-widgets.html

另一种选择是为您的小部件创建一个QtDesigner插件,但这只有在您需要放入多个uis时才有用。

答案 2 :(得分:2)

好吧,现在还没有更好的解决方案,我最后得到了一个QVBoxLayout,其中一个单元格中有一个间隔符:

enter image description here

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)
相关问题