Qt customizes the right-click menu bar of textBrowser

Problem Description

  We use the code to directly generate MainWindowthe right-click menu bar ( how to generate the right-click menu? ), but found that because the textBrowsercontrol defines its own default right-click menu, our customized right-click menu is invalid. As shown below:

Solution

   QWidget and its subclasses can have a right-click menu. First, set the function setContextMenuPolicy() related to the right-click menu of QWidget, and the attribute corresponding item is contextmenuPolicy. The parameter of the setContextMenuPolicy function is the enumerated type Qt::ContextMenuPolicy, which is described in the qt help document:

  Then we enter the UI editing interface, click textBrowseron the parameter that needs to be set, and find the parameter in the property bar on the right, and observe that the parameter defaults to DefaultContextMenu, as shown below:

  This value indicates that when the right-click response is not overwritten, the output is based on the default value, which is why the default menu is displayed. In order to avoid complex rewriting, and when only one right-click menu bar is needed globally, we modify the parameter of the designated control to be ActionsContextMenuthat the menu only needs to be created normally, and the function does not need to be rewritten. At the same time, in order to ensure that the right-click menu does not appear in other non-designated positions, just set this parameter of other controls to PreventContextMenube.
  Finally get the normal custom right-click menu, as shown below:

Some articles about right-click menu rewriting

Qt learning to add menu ActionsContextMenu method to QPushButton
(four) Qt right-click menu
Qt five ways to implement the right-click menu! (take QListWidget as an example)
qt right-click menu event

Guess you like

Origin blog.csdn.net/m0_46161993/article/details/108490339