Unsolved Qt Context Menu Text Edit Within QTreeWidgetItem
-
I'm trying to figure out the best way to change the standard context menu of a text edit. For instance, I have a QTreeWidget and when I edit a QTreeItem I am able to change the text data of that QTreeItem. If I right click while editing that text a standard context menu pops up, how do I change this standard context menu of the text edit?
In general I can use,
connect( m_treeWgtItem, SIGNAL( customContextMenuRequested(const & QPoint) ), m_treeWidget, SLOT( OnContextMenu( const & QPoint) );
to set the context menu of the QTreeWidgetItem, but what signal do I use to set the menu of the text edit of said item?
-
Hi and welcome to devnet,
You can create your own subclass of the editor in order to reimplement contextMenuEvent.
-
class ContextMenuDelegate : public QStyledItemDelegate { Q_OBJECT Q_DISABLE_COPY_MOVE(ContextMenuDelegate) public: using QStyledItemDelegate::QStyledItemDelegate; QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const override{ QWidget* result = QStyledItemDelegate::createEditor(parent,option,index); if(result){ result->setContextMenuPolicy(Qt::CustomContextMenu); connect(result,&QWidget::customContextMenuRequested,this,&ContextMenuDelegate::customContextMenuRequested); } return result; } Q_SIGNALS: void customContextMenuRequested(const QPoint &pos); };
To use it:
contextDelegate = new ContextMenuDelegate(this); treeWidget->setItemDelegate(contextDelegate); connect(contextDelegate,&ContextMenuDelegate::customContextMenuRequested,this,&MyClass::onContextMenu);
You can create your own subclass of the editor
Valid but you would still need a delegate to create this subclass so might as well just subclass the delegate
-
@VRonin said in Qt Context Menu Text Edit Within QTreeWidgetItem:
Valid but you would still need a delegate to create this subclass so might as well just subclass the delegate
Agreed, I was mainly thinking about keeping the customization together with the editor itself.
Your delegate is quite a good solution :-)