how can I keep a QPushbutton selected and then find what is selected in a grid of buttons (pyQt)

StackOverflow https://stackoverflow.com/questions/11776347

  •  24-06-2021
  •  | 
  •  

سؤال

#!!/usr/bin/python

# Qt modules
from PyQt4 import QtCore, QtGui
import sys

class gui(QtGui.QDialog):
    def __init__(self, parent=None):
        QtGui.QDialog.__init__(self, parent)

        self.setWindowTitle('Grid of buttons')
        self.resize(450, 300)


#------------------------------------------------------------------------------ 
#       WIDGETS
#------------------------------------------------------------------------------

        self.grid = QtGui.QGridLayout()

        btnNum = 1
        columnCount = 0
        rowCount = 0

        while btnNum != 26:
            button = QtGui.QPushButton(str(btnNum))
            self.grid.addWidget(button, rowCount, columnCount)
            btnNum += 1

            if columnCount == 4:
                columnCount = 0
                rowCount += 1
            else:
                columnCount += 1

#------------------------------------------------------------------------------ 
#       LAYOUT
#------------------------------------------------------------------------------ 
        self.idChannelGroup = QtGui.QGroupBox("My Button Layout")
        self.idChannelGroup.setLayout(self.grid)

        self.mainLayout = QtGui.QVBoxLayout()
        self.mainLayout.addWidget(self.idChannelGroup)

        self.setLayout(self.mainLayout)   

def main():

    app = QtGui.QApplication(sys.argv)
    ex = gui()
    ex.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

Hi all... I've two questions regarding the use of QPushButton. I am pretty new to Qt so I apologies in advance if these seem a little daft...

Firstly, is there any way to keep the QPushButton depressed i.e. remains selected?

Secondly, query all the buttons and find out which button is presently the selected one? Assuming that it would release when another button is clicked? So there would only ever be a single button selected.

Any help would be great. Thank you.

Cheers

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

المحلول

Firstly, is there any way to keep the QPushButton depressed i.e. remains selected?

Yes, you make it 'checkable' (setCheckable(true)), it is 'down' when 'checked'.

... So there would only ever be a single button selected.

For that, just add your buttons to a QButtonGroup. It defaults to being exclusive, so clicking one will unpress any other.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top