Search code examples
windowsqtmenutitlebarqdialog

Add custom action to System Menu in a QDialog


I have a need to add a custom action (say ‘About’ clicking which a QMessageBox needs to be displayed) in the system menu shown when the icon on the title bar of a QDialog is clicked. How do I achieve this?

Regards, Bharath

Window components


Solution

  • You cannot do it with Qt because it's OS specific. But you can use GetSystemMenu and AppendMenu functions in Windows to modify the menu and then catch events that then item is clicked.

    Here is a simple example from here. It appends a separator and an about item to the menu:

    #include "windows.h"
    
    // IDM_ABOUTBOX must be in the system command range
    //       (IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX)
    //   and (IDM_ABOUTBOX < 0xF000)
    #define IDM_ABOUTBOX 0x0010
    
    MyWidget::MyWidget() : QMainWindow()
    {
     ...
    HMENU hMenu = ::GetSystemMenu(winId(), FALSE);
    if (hMenu != NULL)
    {
      ::AppendMenuA(hMenu, MF_SEPARATOR, 0, 0);
      ::AppendMenuA(hMenu, MF_STRING, IDM_ABOUTBOX, "About MyApp...");
    }
    
    ...
    }
    
    bool MyWidget::winEvent(MSG *m, long *result)
    {
       if (m->message == WM_SYSCOMMAND)
       {
         if ((m->wParam & 0xfff0) == IDM_ABOUTBOX)
         {
            *result = 0;
            // open About dialog
            about();
            return (true);
         }
       }
    
      return (false);
    }
    
    PRO-file:
    LIBS += -lUser32