QPushButton mutually exclusive selection

demand

When we are using QT's QPushButton, there may be mutually exclusive requirements. Only one of them can be selected, and a different background image must be loaded after pressing.

For example, when choosing between men and women, you can only choose one of the two. After the selection, the state of the button is the selected state, and the other button is restored to the unselected state.

I found a picture on the Internet as follows:
Insert picture description here

For the convenience of verification, we use QT designer.

QButtonGroup

Here we will use the QButtonGroup class,
The QButtonGroup class provides a container to organize groups of button widgets.

This class provides a container for managing buttons.

step

0. Drag two buttons to the main UI and change the size of the two to the size of the picture when cutting the picture

1. In QT designer, we select two buttons at the same time, right-click and assign to the button group

2. Add resource file
Cut the picture above into four png format pictures of the same size and add them to the resource file of the project.

3. Add style sheet,
right click "male" button —> change style sheet...

QPushButton{
			border-image: url(:/manV.png);} //空心图片
QPushButton:checked{
			border-image: url(:/man.png);}  //黑心图片

Right-click "Female" button—> Change style sheet...

QPushButton{
			border-image: url(:/womanV.png);} //空心图片
QPushButton:checked{
			border-image: url(:/woman.png);}  //黑心图片

4. Set the attribute checkable

Set the chechable attribute of the two buttons to enable, and then set the checked attribute of one of them to enable.

Remarks:

1. QPushButton: checked is the pressed state

2. The border-image attribute image will stretch with the size of the control.

Guess you like

Origin blog.csdn.net/amwha/article/details/85873921