Adjust of QAction in a QToolBar to fit certain distances in pixels
-
I'm having some problem in adjust the specificity of my task according to distances in pixels. I have QActions that shows only the icons in a QToolBar. The inner QIcon needs to have a 24 x 24 pixels dimensions, the QAction 40 x 40 pixels dimension (So the button needs to have a 40 x 40 and there is a icon inside the button with only 24 x 24) and the QActions need to be separated by 16 pixels.
I tryed adjust the QAction button size with
_ui.myToolBar->setStyleSheet("QToolButton {background-color: red; width: 40px; height: 40px;}");
It seems that size goes to 49 x 49 px. I tried with 20 and 10 pixels and always the button increased by 9 pixels in width and height for some reason. Also I don't know how the resize the Icon with the stylesheet, could you provide some guidance?
-
Unfortunately the little extra you're getting seems to come from the platform plugin and it's hardcoded there, which kinda sucks. What's worse the value is different for different styles, e.g. on Windows it's (7,6). If you're using stylesheet it's (3,3) and so on.
If you don't need to use stylesheet then you can create a proxy style and implement QProxyStyle::sizeFromContents to return the exact size you give it for content type
QStyle::CT_ToolButton
.If you need stylesheets then you can workaround it by calculating the difference between the size you want and the size the style gives you, and set the button size to be smaller by the amount of difference. Something like this:
QToolButton* tb = _ui.myToolBar->findChild<QToolButton*>(); if (tb) { QStyleOptionToolButton opt; opt.initFrom(tb); QSize desired_size {40,40}; QSize style_size = tb->style()->sizeFromContents(QStyle::CT_ToolButton, &opt, desired_size, tb); QSize size_delta = style_size - desired_size; QSize effective_size = desired_size - size_delta; _ui.myToolBar->setIconSize(effective_size); }
Just make sure you call this after you have at least one action already added to the toolbar and you're not setting the size in the stylesheet, because it will have precedence over
setIconSize
.Or you can make sure the extra (9,9) you're getting is also hardcoded in the platform plugin you are using and just subtract that, but that's a bit dangerous if the value changes one day.
-
@Chris-Kawa Thanks for the answer, I know its another Question, but it's the only problem left. My separators's height are not adjusting according to the stylesheet:
_ui.myToolBar->setStyleSheet("QToolBar::separator { background-color: black; margin-left: 8px; margin-right: 8px; height: 30px;}");
The other properties work fine. Any Idea?
-
Apparently separator will always fill the height of the toolbar (or width for vertical toolbars). You can limit it by adding top/bottom margins, so if your toolbar is 40px and you want the separator to be 30px add 5px top and bottom margins.