Solved 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.
-
Hi
Im not sure what margins you mean but you can always add some properties
https://doc.qt.io/qt-5/properties.html
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.wid1Layout.addWidget(self.lab1) self.wid1.setLayout(self.wid1Layout) self.wid2 = QWidget() self.wid2.setMaximumSize(150, 150) self.wid2.setStyleSheet("background: teal;") self.wid2Layout = QHBoxLayout() self.wid2Layout.addWidget(self.lab2) self.wid2.setLayout(self.wid2Layout) self.layout = QHBoxLayout() self.layout.addWidget(self.wid1) self.layout.addWidget(self.wid2) self.setLayout(self.layout) 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.setDuration(200) self.decMarginAnim.setEndValue(QMargins(0, 0, 0, 0)) self.decMarginAnim.start() def enterEvent(self, event): self.decMargin() if __name__ == '__main__': app = QApplication(sys.argv) mw = MainWindow() mw.show() sys.exit(app.exec_())
Would you mind helping me out here with adding the property ?
-
Hi
You can see the syntax here
https://wiki.qt.io/Qt_for_Python_UsingQtPropertiesIm not sure QPropertyAnimation understands the contentsMargins directly as it 4 ints and not a QRect like
GeometryI was thinking of
def readPP(self): return self.ppval def setPP(self,val): self.ppval = val self.wid2.setContentsMargins(val,val,val,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.