Lukas Greblikas
Lukas Greblikas

Reputation: 669

Using QAction with QLabel and creating accordion using QStackedWidget

I am trying to add QAction object to QLabel object using QLabel.addAction() method, but it doesn't seem to work. Is it not supposed to work or am I doing something wrong?

I am trying to make an accordion using QStackedWidget.

enter image description here

For this I need a section title which will either hide or show the title's section when user presses on that title. I could use mouseReleasedEvent, but I would prefer proper QAction toggle() implementation. Maybe I could use something else than QLabel for this matter?

Upvotes: 2

Views: 2776

Answers (1)

NoDataDumpNoContribution
NoDataDumpNoContribution

Reputation: 10859

The addAction functionality of QWidget is used for providing context menus and does not directly relate to an action that is triggered when the mouse is clicked on the label.

You therefore must use some kind of mousexxxevent.

If you prefer signals instead, this is also quite easy:

from PySide.QtGui import *
from PySide.QtCore import *

class ClickableLabel(QLabel):
    """
        A Label that emits a signal when clicked.
    """

    clicked = Signal()

    def __init__(self, *args):
        super().__init__(*args)

    def mousePressEvent(self, event):
        self.clicked.emit()

# example
app = QApplication([])
window = QWidget()
layout = QVBoxLayout(window)
labelA = ClickableLabel('Click on me for more.')
layout.addWidget(labelA)
labelB = QLabel('Here I am.')
layout.addWidget(labelB)
labelB.hide()
labelA.clicked.connect(labelB.show)
window.show()
app.exec_()

Or if you want an action instead, make it like this:

from PySide.QtGui import *
from PySide.QtCore import *

class ClickableLabel(QLabel):
    """
        A Label that emits a signal when clicked.
    """

    def __init__(self, *args):
        super().__init__(*args)

    def mousePressEvent(self, event):
        self.action.triggered.emit()

# example
app = QApplication([])
window = QWidget()
layout = QVBoxLayout(window)
labelA = ClickableLabel('Click on me for more.')
layout.addWidget(labelA)
labelB = QLabel('Here I am.')
layout.addWidget(labelB)
labelB.hide()

action = QAction('Action', labelA)
labelA.action = action
action.triggered.connect(labelB.show)

window.show()
app.exec_()

The example are in Python 3.X notation and for PySide but translation to Python 2.X or PyQt is probably quite simple.

Upvotes: 5

Related Questions