Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. Qt for Python
  4. I can't get keyPressEvent working from __init__
Forum Update on Monday, May 27th 2025

I can't get keyPressEvent working from __init__

Scheduled Pinned Locked Moved Solved Qt for Python
12 Posts 3 Posters 719 Views
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • U user239857
    1 Jun 2023, 03:12

    My application is laid out so almost everything is inside init, but I can't get keyPressEvent to register from within init.

    If I pull it back one tab in scope, it works, but that breaks the rest of the application.

    Is there something I can do to have the keyPressEvent work from within init or do I have to re-scope most of my application?

    class Widget(QWidget):
    
    	def __init__(self, parent=None):
    
    		super().__init__(parent)
    		self.ui = Ui_Widget()
    		self.ui.setupUi(self)
    
    		# OPTION A: Doesn't work, but preferred
    		def keyPressEvent(self, event):
    					print(event.key())
    
    	# OPTION B: Works
    	def keyPressEvent(self, event):
    		print(event.key())
    
    if __name__ == "__main__":
    
    	app = QApplication(sys.argv)
    	widget = Widget()
    	widget.show()
    	sys.exit(app.exec())
    
    J Offline
    J Offline
    jsulm
    Lifetime Qt Champion
    wrote on 1 Jun 2023, 05:35 last edited by jsulm 6 Jan 2023, 05:36
    #2

    @user239857 said in I can't get keyPressEvent working from __init__:

    I can't get keyPressEvent to register from within init.

    How should that work?!
    If you define keyPressEvent inside init then it only exists inside init, so Qt will not see it and will be not able to call it.
    Why do you want to define methods inside init?

    https://forum.qt.io/topic/113070/qt-code-of-conduct

    1 Reply Last reply
    2
    • U user239857
      1 Jun 2023, 03:12

      My application is laid out so almost everything is inside init, but I can't get keyPressEvent to register from within init.

      If I pull it back one tab in scope, it works, but that breaks the rest of the application.

      Is there something I can do to have the keyPressEvent work from within init or do I have to re-scope most of my application?

      class Widget(QWidget):
      
      	def __init__(self, parent=None):
      
      		super().__init__(parent)
      		self.ui = Ui_Widget()
      		self.ui.setupUi(self)
      
      		# OPTION A: Doesn't work, but preferred
      		def keyPressEvent(self, event):
      					print(event.key())
      
      	# OPTION B: Works
      	def keyPressEvent(self, event):
      		print(event.key())
      
      if __name__ == "__main__":
      
      	app = QApplication(sys.argv)
      	widget = Widget()
      	widget.show()
      	sys.exit(app.exec())
      
      J Offline
      J Offline
      JonB
      wrote on 1 Jun 2023, 05:46 last edited by
      #3

      @user239857 said in I can't get keyPressEvent working from __init__:

      My application is laid out so almost everything is inside init

      This makes no sense, so stop doing it.

      U 1 Reply Last reply 1 Jun 2023, 06:28
      0
      • J JonB
        1 Jun 2023, 05:46

        @user239857 said in I can't get keyPressEvent working from __init__:

        My application is laid out so almost everything is inside init

        This makes no sense, so stop doing it.

        U Offline
        U Offline
        user239857
        wrote on 1 Jun 2023, 06:28 last edited by
        #4

        I'm sorry, I'm ~500 lines in having procrastinated learning how to properly scope it.

        I'm not sure of the correct way to do this. I started another app on a fresh project file to experiment.

        When I def functions outside of init, it can't find the ui when I try to refer to it. When I have self.ui.widgets calls outside of init, it can't find 'self' because of scope.

        The last time I used Qt Creator the sample boilerplate code a new project comes with was different from what I'm accustomed to.

        J J 2 Replies Last reply 1 Jun 2023, 06:30
        0
        • U user239857
          1 Jun 2023, 06:28

          I'm sorry, I'm ~500 lines in having procrastinated learning how to properly scope it.

          I'm not sure of the correct way to do this. I started another app on a fresh project file to experiment.

          When I def functions outside of init, it can't find the ui when I try to refer to it. When I have self.ui.widgets calls outside of init, it can't find 'self' because of scope.

          The last time I used Qt Creator the sample boilerplate code a new project comes with was different from what I'm accustomed to.

          J Offline
          J Offline
          jsulm
          Lifetime Qt Champion
          wrote on 1 Jun 2023, 06:30 last edited by jsulm 6 Jan 2023, 06:31
          #5

          @user239857 said in I can't get keyPressEvent working from __init__:

          When I have self.ui.widgets calls outside

          Please show the code where you're doing this. It should work just fine if the method where you're doing this also has self as first parameter.
          self.ui.widgets - is there anything in your ui called "widgets"?

          https://forum.qt.io/topic/113070/qt-code-of-conduct

          1 Reply Last reply
          0
          • U user239857
            1 Jun 2023, 06:28

            I'm sorry, I'm ~500 lines in having procrastinated learning how to properly scope it.

            I'm not sure of the correct way to do this. I started another app on a fresh project file to experiment.

            When I def functions outside of init, it can't find the ui when I try to refer to it. When I have self.ui.widgets calls outside of init, it can't find 'self' because of scope.

            The last time I used Qt Creator the sample boilerplate code a new project comes with was different from what I'm accustomed to.

            J Offline
            J Offline
            JonB
            wrote on 1 Jun 2023, 06:31 last edited by JonB 6 Jan 2023, 06:32
            #6

            @user239857 said in I can't get keyPressEvent working from __init__:

            When I def functions outside of init, it can't find the ui when I try to refer to it. When I have self.ui.widgets calls outside of init, it can't find 'self' because of scope.

            This is standard and basic Python. If there is no self it is not inside a class. Your methods need to be inside the same class as __init__() is, but not inside __init__().

            1 Reply Last reply
            0
            • U Offline
              U Offline
              user239857
              wrote on 1 Jun 2023, 06:42 last edited by user239857 6 Jan 2023, 06:44
              #7

              I suspect the solution isn't much more than a cut/paste away and is probably indicative of a severe lack of understanding of fundamental boilerplate stuff, which I apologize for.

              class Widget(QWidget):
              
              	def __init__(self, parent=None):
              		super().__init__(parent)
              		self.ui = Ui_Widget()
              		self.ui.setupUi(self)
              
              	def hello_world():
              		print("Hello world")
              
              	self.ui.pushButton.pressed.connect(hello_world)
              
              if __name__ == "__main__":
              
              	app = QApplication(sys.argv)
              	widget = Widget()
              	widget.show()
              	sys.exit(app.exec())
              

              Traceback (most recent call last):
              File "widget.py", line 12, in <module>
              class Widget(QWidget):
              File "widget.py", line 22, in Widget
              self.ui.pushButton.pressed.connect(hello_world)
              NameError: name 'self' is not defined

              J 1 Reply Last reply 1 Jun 2023, 06:45
              0
              • U user239857
                1 Jun 2023, 06:42

                I suspect the solution isn't much more than a cut/paste away and is probably indicative of a severe lack of understanding of fundamental boilerplate stuff, which I apologize for.

                class Widget(QWidget):
                
                	def __init__(self, parent=None):
                		super().__init__(parent)
                		self.ui = Ui_Widget()
                		self.ui.setupUi(self)
                
                	def hello_world():
                		print("Hello world")
                
                	self.ui.pushButton.pressed.connect(hello_world)
                
                if __name__ == "__main__":
                
                	app = QApplication(sys.argv)
                	widget = Widget()
                	widget.show()
                	sys.exit(app.exec())
                

                Traceback (most recent call last):
                File "widget.py", line 12, in <module>
                class Widget(QWidget):
                File "widget.py", line 22, in Widget
                self.ui.pushButton.pressed.connect(hello_world)
                NameError: name 'self' is not defined

                J Offline
                J Offline
                JonB
                wrote on 1 Jun 2023, 06:45 last edited by JonB 6 Jan 2023, 06:46
                #8

                @user239857 said in I can't get keyPressEvent working from __init__:

                self.ui.pushButton.pressed.connect(hello_world)

                You cannot have this statement "free-standing" inside a class as you have done. It needs to be inside a method (def method()). Nor can you write hello_world as a free-standing function reference. Please review your Python knowledge.

                The connect() statement does indeed belong inside __init__() in this case:

                    def __init__(self, parent=None):
                        ...
                        self.ui.pushButton.pressed.connect(self.hello_world)
                
                U 1 Reply Last reply 1 Jun 2023, 06:54
                2
                • J JonB
                  1 Jun 2023, 06:45

                  @user239857 said in I can't get keyPressEvent working from __init__:

                  self.ui.pushButton.pressed.connect(hello_world)

                  You cannot have this statement "free-standing" inside a class as you have done. It needs to be inside a method (def method()). Nor can you write hello_world as a free-standing function reference. Please review your Python knowledge.

                  The connect() statement does indeed belong inside __init__() in this case:

                      def __init__(self, parent=None):
                          ...
                          self.ui.pushButton.pressed.connect(self.hello_world)
                  
                  U Offline
                  U Offline
                  user239857
                  wrote on 1 Jun 2023, 06:54 last edited by
                  #9

                  @JonB When I have the connect() statement inside init(), it doesn't seem to recognize anything outside init though. I'm not sure what freestanding means.

                  J 1 Reply Last reply 1 Jun 2023, 06:58
                  0
                  • U user239857
                    1 Jun 2023, 06:54

                    @JonB When I have the connect() statement inside init(), it doesn't seem to recognize anything outside init though. I'm not sure what freestanding means.

                    J Offline
                    J Offline
                    JonB
                    wrote on 1 Jun 2023, 06:58 last edited by JonB 6 Jan 2023, 07:00
                    #10

                    @user239857 said in I can't get keyPressEvent working from __init__:

                    When I have the connect() statement inside init(), it doesn't seem to recognize anything outside init though

                    Nothing to do with being inside __init__(). Members of a class obviously cannot reference objects outside the class without a reference to the other objects.

                    "Freestanding" means a method or variable not inside some class.

                    The code I gave you will work from the code you showed. Did you try it? We don't know what else your new problem might be if you don't show an example of whatever new thing goes wrong.

                    1 Reply Last reply
                    1
                    • U Offline
                      U Offline
                      user239857
                      wrote on 1 Jun 2023, 07:06 last edited by
                      #11

                      Oh and it seems if I place (self) as first param of hello_world it's able to work outside of init. Thank you for your patience, I think this bridges the gap for me!

                      J 1 Reply Last reply 1 Jun 2023, 07:08
                      1
                      • U user239857 has marked this topic as solved on 1 Jun 2023, 07:06
                      • U user239857
                        1 Jun 2023, 07:06

                        Oh and it seems if I place (self) as first param of hello_world it's able to work outside of init. Thank you for your patience, I think this bridges the gap for me!

                        J Offline
                        J Offline
                        JonB
                        wrote on 1 Jun 2023, 07:08 last edited by
                        #12

                        @user239857 said in I can't get keyPressEvent working from __init__:

                        Oh and it seems if I place (self) as first param of hello_world it's able to work outside of init.

                        Sorry, I did not notice you had def hello_world() instead of def hello_world(self), and I forgot my Python! Every (instance) method which is inside a class MUST have self as first parameter in Python (just as your __init__(self, ...) does).

                        1 Reply Last reply
                        0

                        11/12

                        1 Jun 2023, 07:06

                        • Login

                        • Login or register to search.
                        11 out of 12
                        • First post
                          11/12
                          Last post
                        0
                        • Categories
                        • Recent
                        • Tags
                        • Popular
                        • Users
                        • Groups
                        • Search
                        • Get Qt Extensions
                        • Unsolved