Qt 4.8: how to have a QPushButton that looks like a QLabel?

Question:

I want to draw a QPushButton (clickable etc), but have it look like a QLabel. (Another way to see this is I want a clickable label, ie a label that behaves like a button, but that seems more difficult.)

I have tried button.setStyleSheet("QLabel"), doesn’t work.
Is there a way to tell the button to use another style class? or "steal" the style from QLabel?

If possible I would like to avoid redefining the whole style (I do not own the stylesheet, Qt is embedded inside a third-party application), unless this is trivial.

Edit: I ended up using @musicamante’s stylesheet solution, to which I added text-align: left (buttons are centered, labels are not), and :hover/:pressed colors (cyan/blue looks like programmer-art, but serves the purpose :):

QPushButton {
    border: none;
    background: transparent;
    text-align: left;
    color: palette(window-text);
}
QPushButton:hover {
    color: cyan;
}
QPushButton:pressed {
    color: blue;
}
Asked By: benblo

||

Answers:

Styling a button like a label is not usually suggested as it wouldn’t make it clear its state, especially when the mouse button is pressed and released outside the button rectangle.

In any case, it’s enough to set the border property to none, which will also remove the background. Just to be safe and consistent, you could make the background transparent (some style might override it) and ensure that the WindowText color role of the palette is used (instead of the ButtonText role):

button.setStyleSheet("""
    border: none;
    color: palette(window-text);
    background: transparent;
""")

Making a clickable label is not that hard, though, and has the benefit of allowing usage of rich text content, something that a QPushButton cannot do.

class ClickableLabel(QLabel):
    clicked = Signal()
    def mousePressEvent(self, event):
        super(ClickableLabel, self).mousePressEvent(event)
        if event.button() == Qt.LeftButton:
            self.clicked.emit()

Or, to provide consistency with the behavior of a button (as described above, a "click" is considered valid if the mouse button is released within the boundaries of the button rectangle):

class ClickableLabel(QLabel):
    clicked = Signal()
    def mouseReleaseEvent(self, event):
        super(ClickableLabel, self).mouseReleaseEvent(self, event)
        if event.button() == Qt.LeftButton and event.pos() in self.rect():
            self.clicked.emit()
Answered By: musicamante

You can create a custom QLabel, first public inherit a QLabel, then overload the
void mouseReleaseEvent(QMouseEvent *e)

void mouseReleaseEvent(QMouseEvent *e){
    if(e.button == Qt::LeftButton){
          //emit a signal or you want to do when the label are clicked
    }    
}
Answered By: chiZhang
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.