Search code examples
pythonlinuxqtpyqt4numpad

how to assign a key (QtCore.Qt.Key_1) to a button in python. a numeric pad


i have this numpad, i would like to make every numbered button to write its coresponding number on the line above. For example if i enter 1234 by presing on the buttons the same sequence to be displayed on the line. i'm using pyqt4 with qt designer. The line above is a QlineEdit, i import the .ui file directly in the python script i don't convert it using pyuic4. can someone help me find a solution to this? i'm m new to python i started 3 month ago. Thank you

class MyWindow(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        file_path = os.path.abspath("ui/sales_window.ui")
        uic.loadUi(file_path, self)

Solution

  • The first step is to create a button-group for the number-pad.

    In Qt Designer, click on one of the buttons, then Ctrl+click all the other buttons in the number-pad so that they are all selected (twelve buttons in all). Now right-click one of the buttons and select Assign to button group > New button group from the menu. Then save the ui file.

    You can now add a handler to your main script to control the buttons:

    class MyWindow(QtGui.QMainWindow):
        def __init__(self):
            QtGui.QWidget.__init__(self)
            file_path = os.path.abspath("aaa.ui")
            uic.loadUi(file_path, self)
            self.barcode_src_line.setReadOnly(True)
            self.buttonGroup.buttonClicked.connect(self.handleButtons)
    
        def handleButtons(self, button):
            char = str(button.text())
            if char == 'C':
                self.barcode_src_line.clear()
            else:
                text = str(self.barcode_src_line.text()) or '0'
                if char != '.' or '.' not in text:
                    if text != '0' or char == '.':
                        text += char
                    else:
                        text = char
                    self.barcode_src_line.setText(text)
    

    This will work like a normal calculator. If you want different behaviour, you can of course re-write handleButtons in any way you like.