[Python] how to make a button inactive in pyqt?

Discussão em 'Python' iniciado por Stack, Fevereiro 27, 2025.

  1. Stack

    Stack Membro Participativo

    The QMainWindow window contains the QTableView and QPushButton. Necessary :1 when the cell is highlighted, the button will be active setEnabled(True) I did this when connecting the signal . 2 how to do so that if you remove the cell selection, for example, to an empty place in the table, the button changes the mode to setEnabled(False)

    import sys

    from PyQt6.QtGui import QStandardItemModel, QStandardItem
    from PyQt6.QtWidgets import QApplication, QPushButton, QTableView, QVBoxLayout, QWidget


    class MyWindow(QWidget):
    def __init__(self):
    super(MyWindow, self).__init__()
    self.buttonEdit = QPushButton('Edit')
    self.qtable = QTableView()
    self.buttonEdit.setEnabled(False)

    data = [['1', '2', '3'],
    ['4', '5', '6'],
    ['7', '8', '9']]

    self.model = QStandardItemModel()

    for row in range(len(data)):
    for column in range(len(data[row])):
    item = QStandardItem(data[row][column])
    self.model.setItem(row, column, item)

    self.qtable.setModel(self.model)

    self.qtable.selectionModel().selectionChanged.connect(self.on_click)

    self.box = QVBoxLayout()
    self.box.addWidget(self.qtable)
    self.box.addWidget(self.buttonEdit)

    self.setLayout(self.box)

    def on_click(self):
    if self.qtable.selectionModel():
    self.buttonEdit.setEnabled(True)


    if __name__ == '__main__':
    app = QApplication(sys.argv)

    main_window = MyWindow()
    main_window.resize(600, 800)

    main_window.show()
    sys.exit(app.exec())

    Continue reading...

Compartilhe esta Página