PyQt4: How to change the order of child widgets?

I want to implement a GUI program like blueprint editor in Unreal game engine with PyQt4. Here is an example of a drawing editor:

enter image description here

First, I create a simple container widget to house all the components (rectangles). Then I use the QPainterPath

line drawing widget to connect the components. Since users can place components wherever they want by dragging and dropping them, I choose absolute positioning in my container. Here's some sample code:

class Component(QtGui.QWidget):
    """A simple rectangle."""
    def __init__(self, type_, parent=None):
        super(Component, self).__init__(parent)
        ...

class BezierPath(QtGui.QWidget):

    def __init__(self, start, end, parent=None):
        super(BezierPath, self).__init__(parent)
        self.setMinimumSize(300, 500)
        self._start = start
        self._end = end
        self._path = self._generate_path(self._start, self._end)
        self.setMinimumSize(
            abs(start.x()-end.x()), abs(start.y()-end.y()))

    def _generate_path(self, start, end):
        path = QtGui.QPainterPath()
        path.moveTo(start)
        central_x = (start.x()+end.x())*0.5
        path.cubicTo(
            QtCore.QPointF(central_x, start.y()),
            QtCore.QPointF(central_x, end.y()),
            end)
        return path

    def paintEvent(self, event):
        painter = QtGui.QPainter()
        painter.begin(self)
        pen = QtGui.QPen()
        pen.setWidth(3)
        painter.setPen(pen)
        painter.setRenderHint(QtGui.QPainter.Antialiasing, True)
        painter.drawPath(self._path)
        painter.end()

class Container(QtGui.QWidget):
    def add_component(self, component_type, position):
        component = Component(component_type, self)
        component.move(position)

    def add_connection(self, component_a, component_b):
        bezier_path = BezierPath(component_a.pos(), component_b.pose(), self)

      

The problem is I want to show the rows below the components, but the components are created first. Can I change the order of child widgets Container

if I use a better way to organize components?

+3


source to share


1 answer


I found a solution for reordering child widgets. I will mark this answer as is customary at the moment. This is not a perfect solution, so if there is a better answer, then I will agree. Anyway, here's the solution:

In qt4, the widget has a method raise_()

, here I am quoting:



to bring this widget to the top of the parent widget's stack. After this call, the widget will be visually in front of any overlapping sibling widgets.

So, if you want to reorder all of your widgets, first store links to all child widgets in your list or container of your choice. Reorder all widgets in their own container, then call raise_()

for each widget in reverse order.

+1


source







All Articles