Context Menu Event
-
Hi, everyone.
I have a problem on the context menu Event.
I have a window of this kind:
the white box on the left is a textEdit, while the right one is a QTreeWidget.
I've implemented the context menu in the following way:void notepad::contextMenuEvent(QContextMenuEvent *) { QMenu submenu; QString style="QMenu {border-radius:15px; background-color: white;margin: 2px; border: 1px solid rgb(58, 80, 116); color: rgb(58, 80, 116);}QMenu::separator {height: 2px;background: rgb(58, 80, 116);margin-left: 10px;margin-right: 5px;}"; submenu.setStyleSheet(style); submenu.addAction(tr("Copy"),this,¬epad::on_actionCopy_triggered); submenu.addSeparator(); submenu.addAction(tr("Cut"),this,¬epad::on_actionCut_triggered); submenu.addSeparator(); submenu.addAction(tr("Paste"),this,¬epad::on_actionPaste_triggered); submenu.addSeparator(); QPoint globalPos=ui->textEdit->cursor().pos(); submenu.exec(globalPos); }
Everything works, but I would like to show this menu only If I click with the mouse in the textEdit part and not in the part that shows a list of onlineUsers.
How can I do it? -
@Martinuccia_96
You want to place the context menu on the text edit, not on the whole window (notepad
?).QTextEdit
has its own dedicated context menu support --- see https://doc.qt.io/qt-5/qtextedit.html#contextMenuEvent & https://doc.qt.io/qt-5/qtextedit.html#createStandardContextMenu. The other way would be to test the position of theQContextMenuEvent
in your code and only pop up the menu if it's over theQTextEdit
, but I think the former approach seems more appropriate/convenient. -
This is not the usual way to do it, you don't need to reimplement an event.
- add
QMenu *m_textEditContextMenu;
as a private member ofnotepad
- in the constructor of
notepad
add
ui->textEdit->setContextMenuPolicy(Qt::CustomContextMenu); connect(ui->textEdit,&QWidget::customContextMenuRequested,this,¬epad::showTextEditContextMenu); m_textEditContextMenu=new QMenu(this); const auto stylesheet=QStringLiteral("QMenu {border-radius:15px; background-color: white;margin: 2px; border: 1px solid rgb(58, 80, 116); color: rgb(58, 80, 116);}QMenu::separator {height: 2px;background: rgb(58, 80, 116);margin-left: 10px;margin-right: 5px;}"); m_textEditContextMenu->setStyleSheet(stylesheet); m_textEditContextMenu->addAction(tr("Copy"),this,¬epad::on_actionCopy_triggered); m_textEditContextMenu->addSeparator(); m_textEditContextMenu->addAction(tr("Cut"),this,¬epad::on_actionCut_triggered); m_textEditContextMenu->addSeparator(); m_textEditContextMenu->addAction(tr("Paste"),this,¬epad::on_actionPaste_triggered); m_textEditContextMenu->addSeparator();
- create a private slot
void showTextEditContextMenu(const QPoint &pos){ m_textEditContextMenu->popup(ui->textEdit->mapToGlobal(pos)); }
- add
-
THANKS SO MUCH!