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. How do I get keyPressEvent on a QLabel?
Forum Updated to NodeBB v4.3 + New Features

How do I get keyPressEvent on a QLabel?

Scheduled Pinned Locked Moved Unsolved Qt for Python
11 Posts 5 Posters 888 Views 2 Watching
  • 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.
  • G Offline
    G Offline
    Geuse
    wrote on last edited by
    #1

    I'm sorry if I'm flooding the forum with my posts by now. But I'm getting stuck.
    This is another script which I actually would rather run outside of Maya, but I haven't been able to create an executable of it. So until I figure that out I'm just running it from Maya because that's what I'm used to.

    So it's a file search UI and it works as intended, (but clearly not the most optimal search solution).
    Now, I managed to create custom QLabels and adding them to a listwidget. I then overload the double mouse button click on the label to open exlorer and navigate to the directory. But I also would like to implement so that I can press enter too.
    Now this is where I get stuck. I haven't succeded in implementing this. What are the steps I need to to to get this working?
    At the bottom I have a method "keyPressEvent", but clearly incorrect.

    # usage: run this:
    '''
    import dag_findFiles
    from imp import reload
    reload(dag_findFiles)
    
    if __name__ == "__main__":
        try:
            test_dialog.close()
            test_dialog.deleteLater()
        except:
            pass
    
        test_dialog = dag_findFiles.MainWindow()
        test_dialog.show()
    '''
    
    
    import sys
    from PySide2.QtWidgets import QApplication, QWidget, QLabel, QLineEdit, QVBoxLayout, QPushButton, QCheckBox, QFileDialog, QScrollArea
    import os
    
    from PySide2 import QtWidgets, QtGui, QtCore
    from functools import partial
    import maya.OpenMayaUI as omui
    from shiboken2 import wrapInstance
    from functools import partial
    
    def maya_main_window():
        main_window_ptr = omui.MQtUtil.mainWindow()
        return wrapInstance(int(main_window_ptr), QWidget)    
        
        
    class MainWindow(QtWidgets.QMainWindow):
        qLabels = []
        def __init__(self, parent=maya_main_window()):
            super(MainWindow, self).__init__(parent)
            self.init_ui()
    
        def init_ui(self):
            
            self.setWindowTitle("Find Files")
            self.setMinimumSize(400, 200)
            
            directory_label = QLabel("Directory:")
            self.directory_edit = QLineEdit()
            self.browse_button = QPushButton("Browse")
            self.browse_button.clicked.connect(self.browse_directory)
            search_word_label = QLabel("Search Word:")
            self.search_word_edit = QLineEdit()
            self.folder_checkbox = QCheckBox("Folders")
            self.folder_checkbox.setChecked(True)
            self.file_checkbox = QCheckBox("Files")
            self.file_contents_checkbox = QCheckBox("File Contents")
            self.search_button = QPushButton("Search")
            self.search_button.clicked.connect(self.find_files)
            
            self.layout = QVBoxLayout()
            self.layout.addWidget(directory_label)
            self.layout.addWidget(self.directory_edit)
            self.layout.addWidget(self.browse_button)
            self.layout.addWidget(search_word_label)
            self.layout.addWidget(self.search_word_edit)
            self.layout.addWidget(self.folder_checkbox)
            self.layout.addWidget(self.file_checkbox)
            self.layout.addWidget(self.file_contents_checkbox)
            self.layout.addWidget(self.search_button)
            
            self.listWidget = QtWidgets.QListWidget()
            self.layout.addWidget(self.listWidget)       
            
            
            central_widget = QtWidgets.QWidget()
            central_widget.setLayout(self.layout)
            self.setCentralWidget(central_widget)
            
            '''
            for i in range(10):
                label = ClickableLabel(str(i))
                #self.scrollAreaLayout.addWidget(label)
                QtWidgets.QListWidgetItem('ITEM-%04d'%i, self.listWidget)
            '''
        
        def browse_directory(self):
            directory = QFileDialog.getExistingDirectory(self, "Select Directory")
            self.directory_edit.setText(directory)
    
        def openDir():
            print(f'dir open:')
    
        def find_files(self):
            # clear listwidget
            self.listWidget.clear()
            
            directory = self.directory_edit.text()
            search_word = self.search_word_edit.text()
            matches = []
            # folder search
            if self.folder_checkbox.isChecked():
                for root, dirs, files in os.walk(directory):
                    for folder in dirs:
                        if search_word.lower() in folder.lower():
                            folder_path = os.path.join(root, folder)
                            matches.append(f"{folder_path}")
            # file search
            if self.file_checkbox.isChecked():
                for root, dirs, files in os.walk(directory):
                    for file in files:
                        if search_word.lower() in file.lower():
                            file_path = os.path.join(root, file)
                            matches.append(f"{file_path}")
            # file content search
            if self.file_contents_checkbox.isChecked():
                for root, dirs, files in os.walk(directory):
                    for file in files:
                        file_path = os.path.join(root, file)
                        with open(file_path, "r") as f:
                            contents = f.read()
                            if search_word.lower() in contents.lower():
                                matches.append(f"{file_path}")
    
    
    
            '''                            
            if matches:
                result = "\n".join(matches)
            else:
                result = "No matches found."
            self.result_label.setText(result)
            '''
            for match in matches:           
                myItem = ClickableLabel(match)
                item = QtWidgets.QListWidgetItem()
                #item.setSizeHint(QtCore.QSize(0,5))
                self.listWidget.addItem(item)
                self.listWidget.setItemWidget(item, myItem)
    
    
    # custom QLabel
    class ClickableLabel(QLabel):
        def __init__(self, parent=None):
            super(ClickableLabel, self).__init__(parent)
    
        # override mouse double-click to open explorer and navigate to the directory
        def mouseDoubleClickEvent(self, event):
            if event.buttons() == QtCore.Qt.LeftButton:
                path = os.path.normpath(str(self.text()))
                print(path)
                os.startfile(path)
                
        def keyPressEvent(self, event):
            if event.key() == QtCore.Qt.Key_Enter:
                path = os.path.normpath(str(self.text()))
                print(path)
                os.startfile(path)
    
    jsulmJ 1 Reply Last reply
    0
    • G Geuse

      I'm sorry if I'm flooding the forum with my posts by now. But I'm getting stuck.
      This is another script which I actually would rather run outside of Maya, but I haven't been able to create an executable of it. So until I figure that out I'm just running it from Maya because that's what I'm used to.

      So it's a file search UI and it works as intended, (but clearly not the most optimal search solution).
      Now, I managed to create custom QLabels and adding them to a listwidget. I then overload the double mouse button click on the label to open exlorer and navigate to the directory. But I also would like to implement so that I can press enter too.
      Now this is where I get stuck. I haven't succeded in implementing this. What are the steps I need to to to get this working?
      At the bottom I have a method "keyPressEvent", but clearly incorrect.

      # usage: run this:
      '''
      import dag_findFiles
      from imp import reload
      reload(dag_findFiles)
      
      if __name__ == "__main__":
          try:
              test_dialog.close()
              test_dialog.deleteLater()
          except:
              pass
      
          test_dialog = dag_findFiles.MainWindow()
          test_dialog.show()
      '''
      
      
      import sys
      from PySide2.QtWidgets import QApplication, QWidget, QLabel, QLineEdit, QVBoxLayout, QPushButton, QCheckBox, QFileDialog, QScrollArea
      import os
      
      from PySide2 import QtWidgets, QtGui, QtCore
      from functools import partial
      import maya.OpenMayaUI as omui
      from shiboken2 import wrapInstance
      from functools import partial
      
      def maya_main_window():
          main_window_ptr = omui.MQtUtil.mainWindow()
          return wrapInstance(int(main_window_ptr), QWidget)    
          
          
      class MainWindow(QtWidgets.QMainWindow):
          qLabels = []
          def __init__(self, parent=maya_main_window()):
              super(MainWindow, self).__init__(parent)
              self.init_ui()
      
          def init_ui(self):
              
              self.setWindowTitle("Find Files")
              self.setMinimumSize(400, 200)
              
              directory_label = QLabel("Directory:")
              self.directory_edit = QLineEdit()
              self.browse_button = QPushButton("Browse")
              self.browse_button.clicked.connect(self.browse_directory)
              search_word_label = QLabel("Search Word:")
              self.search_word_edit = QLineEdit()
              self.folder_checkbox = QCheckBox("Folders")
              self.folder_checkbox.setChecked(True)
              self.file_checkbox = QCheckBox("Files")
              self.file_contents_checkbox = QCheckBox("File Contents")
              self.search_button = QPushButton("Search")
              self.search_button.clicked.connect(self.find_files)
              
              self.layout = QVBoxLayout()
              self.layout.addWidget(directory_label)
              self.layout.addWidget(self.directory_edit)
              self.layout.addWidget(self.browse_button)
              self.layout.addWidget(search_word_label)
              self.layout.addWidget(self.search_word_edit)
              self.layout.addWidget(self.folder_checkbox)
              self.layout.addWidget(self.file_checkbox)
              self.layout.addWidget(self.file_contents_checkbox)
              self.layout.addWidget(self.search_button)
              
              self.listWidget = QtWidgets.QListWidget()
              self.layout.addWidget(self.listWidget)       
              
              
              central_widget = QtWidgets.QWidget()
              central_widget.setLayout(self.layout)
              self.setCentralWidget(central_widget)
              
              '''
              for i in range(10):
                  label = ClickableLabel(str(i))
                  #self.scrollAreaLayout.addWidget(label)
                  QtWidgets.QListWidgetItem('ITEM-%04d'%i, self.listWidget)
              '''
          
          def browse_directory(self):
              directory = QFileDialog.getExistingDirectory(self, "Select Directory")
              self.directory_edit.setText(directory)
      
          def openDir():
              print(f'dir open:')
      
          def find_files(self):
              # clear listwidget
              self.listWidget.clear()
              
              directory = self.directory_edit.text()
              search_word = self.search_word_edit.text()
              matches = []
              # folder search
              if self.folder_checkbox.isChecked():
                  for root, dirs, files in os.walk(directory):
                      for folder in dirs:
                          if search_word.lower() in folder.lower():
                              folder_path = os.path.join(root, folder)
                              matches.append(f"{folder_path}")
              # file search
              if self.file_checkbox.isChecked():
                  for root, dirs, files in os.walk(directory):
                      for file in files:
                          if search_word.lower() in file.lower():
                              file_path = os.path.join(root, file)
                              matches.append(f"{file_path}")
              # file content search
              if self.file_contents_checkbox.isChecked():
                  for root, dirs, files in os.walk(directory):
                      for file in files:
                          file_path = os.path.join(root, file)
                          with open(file_path, "r") as f:
                              contents = f.read()
                              if search_word.lower() in contents.lower():
                                  matches.append(f"{file_path}")
      
      
      
              '''                            
              if matches:
                  result = "\n".join(matches)
              else:
                  result = "No matches found."
              self.result_label.setText(result)
              '''
              for match in matches:           
                  myItem = ClickableLabel(match)
                  item = QtWidgets.QListWidgetItem()
                  #item.setSizeHint(QtCore.QSize(0,5))
                  self.listWidget.addItem(item)
                  self.listWidget.setItemWidget(item, myItem)
      
      
      # custom QLabel
      class ClickableLabel(QLabel):
          def __init__(self, parent=None):
              super(ClickableLabel, self).__init__(parent)
      
          # override mouse double-click to open explorer and navigate to the directory
          def mouseDoubleClickEvent(self, event):
              if event.buttons() == QtCore.Qt.LeftButton:
                  path = os.path.normpath(str(self.text()))
                  print(path)
                  os.startfile(path)
                  
          def keyPressEvent(self, event):
              if event.key() == QtCore.Qt.Key_Enter:
                  path = os.path.normpath(str(self.text()))
                  print(path)
                  os.startfile(path)
      
      jsulmJ Offline
      jsulmJ Offline
      jsulm
      Lifetime Qt Champion
      wrote on last edited by
      #2

      @Geuse said in How do I get keyPressEvent on a QLabel?:

      At the bottom I have a method "keyPressEvent", but clearly incorrect

      Should be OK.
      Is keyPressEvent called?

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

      G 1 Reply Last reply
      0
      • jsulmJ jsulm

        @Geuse said in How do I get keyPressEvent on a QLabel?:

        At the bottom I have a method "keyPressEvent", but clearly incorrect

        Should be OK.
        Is keyPressEvent called?

        G Offline
        G Offline
        Geuse
        wrote on last edited by
        #3

        @jsulm Thank you. No it doesn't seem it gets called. =/

        jsulmJ 1 Reply Last reply
        0
        • G Geuse

          @jsulm Thank you. No it doesn't seem it gets called. =/

          jsulmJ Offline
          jsulmJ Offline
          jsulm
          Lifetime Qt Champion
          wrote on last edited by
          #4

          @Geuse Even this version:

          def keyPressEvent(self, event):
              print("keyPressEvent")
          

          ?

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

          G 1 Reply Last reply
          0
          • jsulmJ jsulm

            @Geuse Even this version:

            def keyPressEvent(self, event):
                print("keyPressEvent")
            

            ?

            G Offline
            G Offline
            Geuse
            wrote on last edited by
            #5

            @jsulm No, it doesn't work =/

            JoeCFDJ 1 Reply Last reply
            0
            • G Geuse

              @jsulm No, it doesn't work =/

              JoeCFDJ Offline
              JoeCFDJ Offline
              JoeCFD
              wrote on last edited by JoeCFD
              #6

              @Geuse Does QLabel react to keyPressEvent?
              Try installEventFilter( this ); use label's parent or grandparent as this? Or change qlabel to a button.

              1 Reply Last reply
              0
              • SGaistS Offline
                SGaistS Offline
                SGaist
                Lifetime Qt Champion
                wrote on last edited by
                #7

                Hi,

                Unless your label has focus, it won't react to key press event.

                Interested in AI ? www.idiap.ch
                Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

                G 1 Reply Last reply
                0
                • SGaistS SGaist

                  Hi,

                  Unless your label has focus, it won't react to key press event.

                  G Offline
                  G Offline
                  Geuse
                  wrote on last edited by
                  #8

                  @SGaist I mean, the label is selected by stepping up and down the items in the list. No?

                  SGaistS 1 Reply Last reply
                  0
                  • G Geuse

                    @SGaist I mean, the label is selected by stepping up and down the items in the list. No?

                    SGaistS Offline
                    SGaistS Offline
                    SGaist
                    Lifetime Qt Champion
                    wrote on last edited by
                    #9

                    @Geuse no, as the documentation says, using setItemWidget should only be used to present static content. The widget is put on top of the cell content but it's not managed by it. If you want full interaction as provided by the view, use a QStyledItemDelegate.

                    Interested in AI ? www.idiap.ch
                    Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

                    G 1 Reply Last reply
                    0
                    • SGaistS SGaist

                      @Geuse no, as the documentation says, using setItemWidget should only be used to present static content. The widget is put on top of the cell content but it's not managed by it. If you want full interaction as provided by the view, use a QStyledItemDelegate.

                      G Offline
                      G Offline
                      Geuse
                      wrote on last edited by
                      #10

                      @SGaist Thank you! I will read up on that and see how far I come.
                      Thank you.

                      jeremy_kJ 1 Reply Last reply
                      0
                      • G Geuse

                        @SGaist Thank you! I will read up on that and see how far I come.
                        Thank you.

                        jeremy_kJ Offline
                        jeremy_kJ Offline
                        jeremy_k
                        wrote on last edited by
                        #11

                        If the goal is only to detect when an item in the list is clicked or has enter pressed, putting the logic in the delegate seems like the wrong way to go.

                        QAbstractItemView::activated(), clicked(), QListWidget::itemActivated(), itemClicked, and several other signals are available to indicate user interaction with the view. If the *activated signals aren't triggered for the target platforms with the desired key and mouse input, override the events in the view, and use QAbstractItemView::indexAt() and currentIndex(), or QListWidget::itemAt() and currentItem().

                        Asking a question about code? http://eel.is/iso-c++/testcase/

                        1 Reply Last reply
                        0

                        • Login

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