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. PyQt5 - QWidgetAction doesn't working when adding html style
Qt 6.11 is out! See what's new in the release blog

PyQt5 - QWidgetAction doesn't working when adding html style

Scheduled Pinned Locked Moved Solved Qt for Python
8 Posts 2 Posters 2.9k 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.
  • PatitotectiveP Offline
    PatitotectiveP Offline
    Patitotective
    wrote on last edited by
    #1

    I'm using QWidgetAction because using QAction i can't add stylesheet. But for some reason using QWidgetAction the shortcut isn't displayed next to it, so decided to add my own.
    I created this function to create QWidgetAction widgets:

    def create_action_widget(self, text: str, menu, stylesheet: str="", callback: callable=lambda: print("No callback"), shortcut: str=""):
    	"""
    	Args:
    		text (str): The text to be displayed in the QWidgetAction.
    		menu (menuBar.addMenu): The menu to append the QWidgetAction.
    		stylesheet (str, optional=""): The stylesheet of the QWidgetAction (really the stylesheet of the Label).
    		callback (callable, optional=lambda: print("No callback")): The callback function to the QWidgetAction.
    		shortcut (str, optional=""): The shortcut to acces to the QWidgetAction
    	"""
    	action = QWidgetAction(self) # Create a QWidget action in QMainWindow
    	
    	if shortcut != "": # If the shortcut isn't empty
    		key = shortcut.split("+")[0] # Split by + and get the modifier key (ctrl, shift, alt)
    		mnemo = shortcut.split("+")[1] # Split by + and get the key (a, b, c)
    		
    		### IF I COMMENT THESE THREE LINES THE QWIDGETACTIONS WORKS ###
    		text = text.replace(mnemo, f"<u>{mnemo}</u>", 1) # Underline the shortut letter 
    		text += f"{'&nbsp;'*3}" # Spacing between given text and shortcut
    		text += f"<span style='color: #ABABAB; font-size: 14px;'>{key}+{mnemo.capitalize()}</span>" # Add different color and font-size to the shortcut
    
    	label = QLabel(text) # Create a QLabel with the text
    	label.setStyleSheet(stylesheet) # Set the given stylesheet to the QLabel
    	action.setDefaultWidget(label); # Set QLabel as default widget to QWidget
    	action.setShortcut(shortcut) # Set shortcut to QWidgetAction
    
    	menu.addAction(action) # Add action to given menu (menuBar.addMenu)
    	action.triggered.connect(callback) # Connect the QWidgetAction with the given callback
    
    	return action # Return the QWidgetAction
    

    But when i added the underlined, the spacing and the different color to the shortcut the callback function when clicking stop working, if i try the shortcut it works but clicking directly into the QWidgetAction doesn't work.

    The whole file is public in my GitHub repo.
    If you want to test the app, make sure you have the requirements.

    jeremy_kJ 1 Reply Last reply
    0
    • PatitotectiveP Patitotective

      @jeremy_k I'm sorry, i don't understand what you're saying. You mean that i have to apply the stylesheet to which widget?
      Can you give me an example?

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

      @Patitotective said in PyQt5 - QWidgetAction doesn't working when adding html style:

      @jeremy_k I'm sorry, i don't understand what you're saying. You mean that i have to apply the stylesheet to which widget?

      Apply the style sheet to the widget displaying the QAction. If you put the QAction in a QMenu, style that QMenu (or a broader selector that will apply to the menu).

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

      PatitotectiveP 1 Reply Last reply
      0
      • PatitotectiveP Patitotective

        I'm using QWidgetAction because using QAction i can't add stylesheet. But for some reason using QWidgetAction the shortcut isn't displayed next to it, so decided to add my own.
        I created this function to create QWidgetAction widgets:

        def create_action_widget(self, text: str, menu, stylesheet: str="", callback: callable=lambda: print("No callback"), shortcut: str=""):
        	"""
        	Args:
        		text (str): The text to be displayed in the QWidgetAction.
        		menu (menuBar.addMenu): The menu to append the QWidgetAction.
        		stylesheet (str, optional=""): The stylesheet of the QWidgetAction (really the stylesheet of the Label).
        		callback (callable, optional=lambda: print("No callback")): The callback function to the QWidgetAction.
        		shortcut (str, optional=""): The shortcut to acces to the QWidgetAction
        	"""
        	action = QWidgetAction(self) # Create a QWidget action in QMainWindow
        	
        	if shortcut != "": # If the shortcut isn't empty
        		key = shortcut.split("+")[0] # Split by + and get the modifier key (ctrl, shift, alt)
        		mnemo = shortcut.split("+")[1] # Split by + and get the key (a, b, c)
        		
        		### IF I COMMENT THESE THREE LINES THE QWIDGETACTIONS WORKS ###
        		text = text.replace(mnemo, f"<u>{mnemo}</u>", 1) # Underline the shortut letter 
        		text += f"{'&nbsp;'*3}" # Spacing between given text and shortcut
        		text += f"<span style='color: #ABABAB; font-size: 14px;'>{key}+{mnemo.capitalize()}</span>" # Add different color and font-size to the shortcut
        
        	label = QLabel(text) # Create a QLabel with the text
        	label.setStyleSheet(stylesheet) # Set the given stylesheet to the QLabel
        	action.setDefaultWidget(label); # Set QLabel as default widget to QWidget
        	action.setShortcut(shortcut) # Set shortcut to QWidgetAction
        
        	menu.addAction(action) # Add action to given menu (menuBar.addMenu)
        	action.triggered.connect(callback) # Connect the QWidgetAction with the given callback
        
        	return action # Return the QWidgetAction
        

        But when i added the underlined, the spacing and the different color to the shortcut the callback function when clicking stop working, if i try the shortcut it works but clicking directly into the QWidgetAction doesn't work.

        The whole file is public in my GitHub repo.
        If you want to test the app, make sure you have the requirements.

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

        QAction doesn't accept a style sheet because it might be displayed in multiple widgets (QMenu, QMenuBar, ...), or not at all. To style the display of the action, apply the style sheet to the widget.

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

        PatitotectiveP 1 Reply Last reply
        0
        • jeremy_kJ jeremy_k

          QAction doesn't accept a style sheet because it might be displayed in multiple widgets (QMenu, QMenuBar, ...), or not at all. To style the display of the action, apply the style sheet to the widget.

          PatitotectiveP Offline
          PatitotectiveP Offline
          Patitotective
          wrote on last edited by Patitotective
          #3

          @jeremy_k I'm sorry, i don't understand what you're saying. You mean that i have to apply the stylesheet to which widget?
          Can you give me an example?

          jeremy_kJ 1 Reply Last reply
          0
          • PatitotectiveP Patitotective

            @jeremy_k I'm sorry, i don't understand what you're saying. You mean that i have to apply the stylesheet to which widget?
            Can you give me an example?

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

            @Patitotective said in PyQt5 - QWidgetAction doesn't working when adding html style:

            @jeremy_k I'm sorry, i don't understand what you're saying. You mean that i have to apply the stylesheet to which widget?

            Apply the style sheet to the widget displaying the QAction. If you put the QAction in a QMenu, style that QMenu (or a broader selector that will apply to the menu).

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

            PatitotectiveP 1 Reply Last reply
            0
            • jeremy_kJ jeremy_k

              @Patitotective said in PyQt5 - QWidgetAction doesn't working when adding html style:

              @jeremy_k I'm sorry, i don't understand what you're saying. You mean that i have to apply the stylesheet to which widget?

              Apply the style sheet to the widget displaying the QAction. If you put the QAction in a QMenu, style that QMenu (or a broader selector that will apply to the menu).

              PatitotectiveP Offline
              PatitotectiveP Offline
              Patitotective
              wrote on last edited by
              #5

              @jeremy_k Applying this stylesheet to the menu, hover is not working.

              *{
              	background: #383838;
              	color: #ABABAB;
              	/*padding: 4px 4px;*/
              	font-size: 15px;
              	}
              
              *:hover{
              	background: #4C4C4C;
              	color: #ffffff;
              }
              *:pressed {
              	background: #595959;
              }
              
              1 Reply Last reply
              0
              • jeremy_kJ Offline
                jeremy_kJ Offline
                jeremy_k
                wrote on last edited by
                #6

                Please post a complete, minimal working example. Just the menu with the action, the style sheet.

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

                PatitotectiveP 1 Reply Last reply
                0
                • jeremy_kJ jeremy_k

                  Please post a complete, minimal working example. Just the menu with the action, the style sheet.

                  PatitotectiveP Offline
                  PatitotectiveP Offline
                  Patitotective
                  wrote on last edited by
                  #7

                  @jeremy_k

                  import sys
                  from PyQt5.QtWidgets import (QApplication, 
                     QAction, QMainWindow, qApp)
                  
                  class MainWindow(QMainWindow):
                     def __init__(self, parent=None):
                        super().__init__(parent)
                        
                        self.create_menu_bar()
                  
                     def create_menu_bar(self):
                        # filling up a menu bar
                        bar = self.menuBar()
                        bar.setStyleSheet(
                           """
                           QMenuBar {
                              background-color: #383838;
                           }
                  
                           QMenuBar::item {
                              padding: 1px 4px;
                              background: transparent;
                              border-radius: 4px;
                              color: #ffffff
                           }
                  
                           QMenuBar::item:selected { /* when selected using mouse or keyboard */
                              background: #4C4C4C;
                           }
                  
                           QMenuBar::item:pressed {
                              background: #595959;
                           }
                           """)
                  
                        menu_stylesheet = """
                           *{
                              background: #383838;
                              color: #ABABAB;
                              /*padding: 4px 4px;*/
                              font-size: 15px;
                              }
                  
                           *:hover{
                              background: #4C4C4C;
                              color: #ffffff;
                           }
                           *:pressed {
                              background: #595959;
                           }
                        """
                  
                        # File menu
                        file_menu = bar.addMenu('&File')
                        file_menu.setStyleSheet(menu_stylesheet)
                        
                        close_action = QAction("Close", self)
                        close_action.setShortcut("Ctrl+Q")
                        close_action.triggered.connect(self.close)
                  
                        file_menu.addAction(close_action)
                  
                  if __name__ == '__main__':
                     app = QApplication(sys.argv)
                     # creating main window
                     mw = MainWindow()
                     mw.show()
                     sys.exit(app.exec_())
                  
                  
                  PatitotectiveP 1 Reply Last reply
                  0
                  • PatitotectiveP Patitotective

                    @jeremy_k

                    import sys
                    from PyQt5.QtWidgets import (QApplication, 
                       QAction, QMainWindow, qApp)
                    
                    class MainWindow(QMainWindow):
                       def __init__(self, parent=None):
                          super().__init__(parent)
                          
                          self.create_menu_bar()
                    
                       def create_menu_bar(self):
                          # filling up a menu bar
                          bar = self.menuBar()
                          bar.setStyleSheet(
                             """
                             QMenuBar {
                                background-color: #383838;
                             }
                    
                             QMenuBar::item {
                                padding: 1px 4px;
                                background: transparent;
                                border-radius: 4px;
                                color: #ffffff
                             }
                    
                             QMenuBar::item:selected { /* when selected using mouse or keyboard */
                                background: #4C4C4C;
                             }
                    
                             QMenuBar::item:pressed {
                                background: #595959;
                             }
                             """)
                    
                          menu_stylesheet = """
                             *{
                                background: #383838;
                                color: #ABABAB;
                                /*padding: 4px 4px;*/
                                font-size: 15px;
                                }
                    
                             *:hover{
                                background: #4C4C4C;
                                color: #ffffff;
                             }
                             *:pressed {
                                background: #595959;
                             }
                          """
                    
                          # File menu
                          file_menu = bar.addMenu('&File')
                          file_menu.setStyleSheet(menu_stylesheet)
                          
                          close_action = QAction("Close", self)
                          close_action.setShortcut("Ctrl+Q")
                          close_action.triggered.connect(self.close)
                    
                          file_menu.addAction(close_action)
                    
                    if __name__ == '__main__':
                       app = QApplication(sys.argv)
                       # creating main window
                       mw = MainWindow()
                       mw.show()
                       sys.exit(app.exec_())
                    
                    
                    PatitotectiveP Offline
                    PatitotectiveP Offline
                    Patitotective
                    wrote on last edited by
                    #8

                    @Patitotective Fixed using:

                    menu_stylesheet = (
                    	"QMenu {"
                    	"	background: #383838;"
                    	"	color: #ABABAB;"
                    	"	font-size: 15px;"
                    	"}"
                    	"QMenu::item:selected {"
                    	"	background: #4C4C4C;"
                    	"	color: #ffffff;"
                    	"}"
                    	"QMenu::item:pressed {"
                    	"	background: #595959;"
                    	"}"
                    )
                    
                    1 Reply Last reply
                    1

                    • Login

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