Important: Please read the Qt Code of Conduct -

How to animate margins of QWidget

  • Is it possible to animate margins of QWidget ? I can't animate the geometry as it is set dynamically. It is not possible to directly animate the margins with QPropertyAnimation but I was thinking if there is an indirect way to animate the margins.

  • Lifetime Qt Champion

    Im not sure what margins you mean but you can always add some properties
    and be able to animate almost any value you like by exposing them as property.

  • @mrjj By margin I mean, the margins that you set to a widget with setContentsMargins. I wanted to animate and decrease it on enterEvent. I couldn't figure out how to add the property and animate it in pyside2. Here is a little something I tried which doesn't work:

    import sys
    from PySide2.QtWidgets import QMainWindow, QWidget, QHBoxLayout, QLabel, QDockWidget, QTabWidget, QApplication
    from PySide2.QtCore import QMargins, QPropertyAnimation
    class MainWindow(QWidget):
        def __init__(self):
            super(MainWindow, self).__init__()
            self.resize(400, 300)
            self.lab1 = QLabel("text for first widget")
            self.lab2 = QLabel("text for second widget")
            self.wid1 = QWidget()
            self.wid1.setMaximumSize(150, 150)
            self.wid1.setStyleSheet("background: orange;")
            self.wid1Layout = QHBoxLayout()
            self.wid2 = QWidget()
            self.wid2.setMaximumSize(150, 150)
            self.wid2.setStyleSheet("background: teal;")
            self.wid2Layout = QHBoxLayout()
            self.layout = QHBoxLayout()
            self.wid1.setContentsMargins(QMargins(8, 8, 8, 8))
            self.wid2.setContentsMargins(QMargins(8, 8, 8, 8))
            self.wid1.setProperty("contentsMargins", self.wid1.contentsMargins())
            self.decMarginAnim = QPropertyAnimation(self.wid1, b"contentsMargins")
        def decMargin(self):
            self.decMarginAnim.setEndValue(QMargins(0, 0, 0, 0))
        def enterEvent(self, event):
    if __name__ == '__main__':
        app = QApplication(sys.argv)
        mw = MainWindow()

    Would you mind helping me out here with adding the property ?

  • Lifetime Qt Champion

    You can see the syntax here

    Im not sure QPropertyAnimation understands the contentsMargins directly as it 4 ints and not a QRect like

    I was thinking of

      def readPP(self):                                                                                   
            return self.ppval             
        def setPP(self,val):                                                                                
             self.ppval = val                                                                                
        pp = Property(int, readPP, setPP)     

    and then we cheat and set setContentsMargins for the int property

  • @mrjj Thanks, it works great. The link helped a lot.

Log in to reply