QGroupBox border

2019-03-18 03:19发布

问题:

After searching for a while I saw that they way to set a visible border on a groupbox is to use the StyleSheet property. I added:

border: 2px solid gray;

but there are a couple of problems.

1) Everything inside the groupbox also inherits this setting!

2) The border has a little hole/piece missing near the title.

Here is a picture of what I'm talking about:

Anyone know how to do this properly?

Thanks,

David

回答1:

The first problem is simple enough When you add a stylesheet to a control it automatically propagates the style to all child widgets. However, you can restrict the use of the style sheet in a couple of ways. You can specify the type of control you want the style sheet to apply to. Example:

QGroupBox { 
     border: 2px solid gray; 
     border-radius: 3px; 
 } 

This style sheet will only be set on Group boxes. However, if you put a second group box inside this one, the style will propagate to this one as well. Which may be good or bad.

Another way is to specifically the objectName of the widget you are applying the style to. Example:

QGroupBox#MyGroupBox { 
     border: 2px solid gray; 
     border-radius: 3px; 
 } 

This will only apply the style to a group box with an object name of MyGroupBox.

As for the space, it is happening because the title is being drawn on top of your border. You can also add a section to your style sheet to change your groupbox title. This includes setting it's background to transparent, and to move the title around to your hearts content.

Example: This will set your title to the top left corner of the group box just inside your border, with no gap.

QGroupBox::title { 
    background-color: transparent;
     subcontrol-position: top left; /* position at the top left*/ 
     padding:2 13px;
 } 


回答2:

this worked for me on Qt 5.1.

qApp->setStyleSheet("QGroupBox {  border: 1px solid gray;}");

Elimeléc



回答3:

Specify a selector for the group box style such as:

QGroupBox
{
     border: 2px solid gray;
}

As for the gap, you can probably fix that by setting some padding. Check the docs here.



标签: qt qt4