qtuitools.rst 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // @snippet quiloader-registercustomwidget
  2. Registers a Python created custom widget to QUiLoader, so it can be recognized
  3. when loading a `.ui` file. The custom widget type is passed via the
  4. ``customWidgetType`` argument. This is needed when you want to override a
  5. virtual method of some widget in the interface, since duck punching will not
  6. work with widgets created by QUiLoader based on the contents of the `.ui` file.
  7. (Remember that
  8. `duck punching virtual methods is an invitation for your own demise! <https://doc.qt.io/qtforpython/shiboken6/wordsofadvice.html#duck-punching-and-virtual-methods>`_)
  9. Let's see an obvious example. If you want to create a new widget it's probable you'll end up
  10. overriding :class:`~PySide6.QtGui.QWidget`'s :meth:`~PySide6.QtGui.QWidget.paintEvent` method.
  11. .. code-block:: python
  12. class Circle(QWidget):
  13. def paintEvent(self, event):
  14. with QPainter(self) as painter:
  15. painter.setPen(self.pen)
  16. painter.setBrush(QBrush(self.color))
  17. painter.drawEllipse(event.rect().center(), 20, 20)
  18. # ...
  19. loader = QUiLoader()
  20. loader.registerCustomWidget(Circle)
  21. circle = loader.load('circle.ui')
  22. circle.show()
  23. # ...
  24. // @snippet quiloader-registercustomwidget
  25. // @snippet loaduitype
  26. .. currentmodule:: PySide6.QtUiTools
  27. loadUiType
  28. ***********
  29. .. py:function:: loadUiType(uifile: str) -> tuple(object, object)
  30. :param str uifile: The name of the `.ui` file
  31. :return: tuple(object, object)
  32. This function generates and loads a `.ui` file at runtime, and it returns
  33. a `tuple` containing the reference to the Python class, and the base class.
  34. We recommend not to use this approach as the workflow should be to generate a Python file
  35. from the `.ui` file, and then import and load it to use it, but we do understand that
  36. there are some corner cases when such functionality is required.
  37. The internal process relies on `uic` being in the PATH.
  38. The `pyside6-uic` wrapper uses a shipped `uic` that is located in the
  39. `site-packages/PySide6/uic`, so PATH needs to be updated to use that if there
  40. is no `uic` in the system.
  41. A simple use case is::
  42. from PySide6.QtUiTools import loadUiType
  43. generated_class, base_class = loadUiType("themewidget.ui")
  44. # the values will be:
  45. # (<class '__main__.Ui_ThemeWidgetForm'>, <class 'PySide6.QtWidgets.QWidget'>)
  46. widget = base_class()
  47. form = generated_class()
  48. form.setupUi(widget)
  49. # form.a_widget_member.a_method_of_member()
  50. widget.show()
  51. // @snippet loaduitype