PDA

View Full Version : How to retrieve margins of a button? [PyQt5]



DDR
8th August 2018, 22:14
Hello everyone,

I've assigned a stylesheet to a button. How would I go about animating the margins? I figure the first step is to retrieve the current margin, since that's what I want to animate to. I can't figure it out though...



from PyQt5 import QtWidgets
QtWidgets.QApplication([])
b = QtWidgets.QPushButton()
b.setStyleSheet("margin: 15px")
b.contentsMargins().top() #is 0, should be 15

The final line produces 0 instead of the expected value of 15.



b.style().subElementRect(QtWidgets.QStyle.SE_PushB uttonFocusRect, QtWidgets.QStyleOptionButton())
b.style().subElementRect(QtWidgets.QStyle.SE_PushB uttonFocusRect, QtWidgets.QStyleOptionButton(), b)

Carrying on, both these lines then print "Segmentation fault" and exit Python. They didn't return anything particularly sensible in my actual app anyway.

Does anyone have any suggestions? I'm trying to make a little 'slide-in' effect for my menu, but I want the buttons to always be clickable even when they haven't slid in yet. I was planning to do it by adjusting the margin-left from my menu width to the original value of margin-left.

Thanks,
–DDR

wysota
20th August 2018, 09:05
Stylesheets are not good for animations and you should avoid using them. If you want a slide animation, use QPropertyAnimation to animation geometry (or x, y) of your buttons.

DDR
30th August 2018, 01:31
Thank you. I was hoping to have the button clickable outside its visual boundaries, as the interface is accessed by a touchscreen. The only real way I know how to do this is by changing the margin and width, so the button appears to slide in but is actually always fully clickable - it makes it so you don't have to wait for the little animation if you know what you're doing by muscle memory. How would you suggest animating the button in, so that the target area is always clickable?

(Sorry for the delayed reply. I thought subscriptions meant "via email", but they were just winding up as a notification in my forum inbox… which I wasn't checking until I got an email.)

wysota
8th September 2018, 09:15
You can use QApplication::setGlobalStrut() to define the minimum size of all interactive parts of a widget in your application. Maybe it suits your needs better than the stylesheet.