سؤال

I need to create a custom push button which will have 3 different background images corresponding to the following states:

  • normal
  • mouse over
  • mouse down

I would like to have a QHBoxLayout with 3 parts for left side, right side and middle side (stretching side) for the button.

Inside the middle size, I would like to have a label to show the text.

I need this button to have a "clicked" event as well.

I have been doing a lot of search to achieve this but I am really lost. I tried many things including custom widget from QWidget or styling QPushButton with stylesheets but I failed to achieve having 3 images for 3 mouse states and the clicked event.

I am looking for help.

هل كانت مفيدة؟

المحلول

You can use the border-image property, by composing a single image for each state like this:

           |              |
Left Image | Middle Image | Right Image
           |              | 

then by specifying the left and right image sizes as the border slice sizes and in the border widths of the stylesheet. For example, if the right images were 25 pixel wide and the left ones 20, you would have:

QPushButton {
    border-image: url(:/normal.png) 0 25 0 20 stretch stretch; 
    border-width:0 25 0 20; /* without it, only the middle images would show */
}
QPushButton:hover { 
    border-image: url(:/hover.png) 0 25 0 20 stretch stretch;
}
QPushButton:pressed { 
    border-image: url(:/pressed.png) 0 25 0 20 stretch stretch;
}

The values represent the distance between the top, right, bottom and left sides of the image.

نصائح أخرى

well,first,you should have 3 picture for 3 states,and then you can use function setStyleSheet .

QPushButton *btn = new QPushButton;
btn->setStyleSheet("QPushButton{background:url(:/Resources/pause_nor.png);border:0px;}"
        "QPushButton:hover{background:url(:/Resources/pause_over.png);border:0px}"
        "QPushButton:pressed{background:url(:/Resources/pause_over.png); position: relative;top: 1px; left: 1px;}");
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top