I am trying to create QTreeWidgetItems with custom context menus. I would like to have QTreeWidget and QTreeWidgetItem derived classes like the following example:
class QCustomTreeWidget;
{
public:
QCustomTreeItem(QCustomTreeWidget *view);
QCustomTreeItem(QCustomTreeItem *parent);
virtual ~QCustomTreeItem();
};
class QMyPluginItem : public QCustomTreeItem
{
public:
QMyPluginItem(QCustomTreeWidget *view);
QMyPluginItem(QCustomTreeItem *parent);
virtual ~QMyPluginItem();
{
// create the context menu
ContextMenu->addAction(actCustom);
connect(actCustom, SIGNAL(triggered(void)), this, SLOT(onCustomAction(void)));
ContextMenu->exec( event->globalPos() );
delete ContextMenu;
}
private slots:
void onCustomAction();
};
{
Q_OBJECT
public:
QCustomTreeWidget
(QWidget *parent
= 0);
virtual ~QCustomTreeWidget();
protected:
{
QCustomTreeItem* selected =
reinterpret_cast<QCustomTreeItem*>(currentItem());
if ( 0 != selected )
selected->onContextMenu(event);
};
};
class QCustomTreeWidget;
class QCustomTreeItem : public QTreeWidgetItem
{
public:
QCustomTreeItem(QCustomTreeWidget *view);
QCustomTreeItem(QCustomTreeItem *parent);
virtual ~QCustomTreeItem();
virtual void onContextMenu(QContextMenuEvent *event) = 0;
};
class QMyPluginItem : public QCustomTreeItem
{
public:
QMyPluginItem(QCustomTreeWidget *view);
QMyPluginItem(QCustomTreeItem *parent);
virtual ~QMyPluginItem();
virtual void onContextMenu(QContextMenuEvent *event)
{
// create the context menu
QMenu* ContextMenu = new QMenu();
QAction *actCustom = new QAction("Custom Action", ContextMenu);
ContextMenu->addAction(actCustom);
connect(actCustom, SIGNAL(triggered(void)), this, SLOT(onCustomAction(void)));
ContextMenu->exec( event->globalPos() );
delete ContextMenu;
}
private slots:
void onCustomAction();
};
class QCustomTreeWidget : public QTreeWidget
{
Q_OBJECT
public:
QCustomTreeWidget(QWidget *parent = 0);
virtual ~QCustomTreeWidget();
protected:
virtual void contextMenuEvent(QContextMenuEvent *event)
{
QCustomTreeItem* selected =
reinterpret_cast<QCustomTreeItem*>(currentItem());
if ( 0 != selected )
selected->onContextMenu(event);
};
};
To copy to clipboard, switch view to plain text mode
I know that Singals and Slots can only work on QObjects. Looking at the documentation and the Qt source, QTreeWidgetItem is not a subclass of QObject (or anything). I dislike multiple inheritance very much, but tried deriving QCustomTreeItem from both QTreeWidgetItem and QObject to add Signal and Slot functionality. I got the following warning:
Warning: Class QCustomTreeItem inherits from two QObject subclasses QTreeWidgetItem and QObject. This is not supported!
If these did not have to be customizable plugin objects, I might just bite the bullet and put a big switch block in QCustomTreeWidget::contextMenuEvent().
Is there a way make the above model work?
Thanks!
Bookmarks