J. D.
J. D.

Reputation: 171

Button Pushed to get Label Text

How do I get the text on label based on the button that is pushed in front of it? Can I somehow get the label widget based on sender().pos()? *Note: I don't want to put text inside the button widget. I want to keep the text as a label in the background.

class FormWidget(QWidget):
    def __init__(self, parent=None):
        super(FormWidget, self).__init__(parent)
        self.grid = QGridLayout(self)
        x = 0
        for i in range(0, 6): # Columns
            for k in range(0, 6): # Rows
                self.PrimaryComboLabel = QLabel()
                self.PrimaryComboLabel.setText(str(x))
                self.grid.addWidget(self.PrimaryComboLabel, k, i, 1, 1, QtCore.Qt.AlignCenter)

                self.PrimaryComboButton = QPushButton('')
                self.grid.addWidget(self.PrimaryComboButton, k, i, 1, 1)
                self.PrimaryComboButton.clicked.connect(lambda: print(self.sender().pos().x(), self.sender().pos().y()))
                self.PrimaryComboButton.setFlat(True)
                self.PrimaryComboButton.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
                x = x + 1

if __name__ == "__main__":
    app = QApplication(sys.argv)
    ex = FormWidget()
    ex.show()
    sys.exit(app.exec_())

Upvotes: 1

Views: 574

Answers (1)

eyllanesc
eyllanesc

Reputation: 243955

You can pass the text as an extra argument to the slot using functools.partial as I pointed out in my previous answer.

import sys
import functools
import itertools

from PyQt5.QtCore import pyqtSlot, Qt
from PyQt5.QtWidgets import (
    QApplication,
    QGridLayout,
    QLabel,
    QPushButton,
    QSizePolicy,
    QWidget,
)


class FormWidget(QWidget):
    def __init__(self, parent=None):
        super(FormWidget, self).__init__(parent)
        grid = QGridLayout(self)
        for i, coords in enumerate(itertools.product(range(6), range(6))):
            j, k = coords
            label = QLabel("{}".format(i))
            button = QPushButton(flat=True)
            button.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
            wrapper = functools.partial(self.on_clicked, label.text())
            button.clicked.connect(wrapper)
            grid.addWidget(label, k, j, 1, 1, alignment=Qt.AlignCenter)
            grid.addWidget(button, k, j, 1, 1)

    @pyqtSlot()
    def on_clicked(self, text):
        print(text)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    ex = FormWidget()
    ex.show()
    sys.exit(app.exec_())

Upvotes: 2

Related Questions