Skip to content

Instantly share code, notes, and snippets.

@benevo
Forked from jmk/example.cpp
Created October 24, 2018 07:16
Show Gist options
  • Save benevo/6744ff36eaf6f952a8741406227cc93c to your computer and use it in GitHub Desktop.
Save benevo/6744ff36eaf6f952a8741406227cc93c to your computer and use it in GitHub Desktop.
Example of showing different context menu for items in a QTreeWidget
#include "main.h"
int main(int argc, char** argv)
{
QApplication app(argc, argv);
MyTreeWidget w;
w.show();
// Add test items.
w.addTopLevelItem(new QTreeWidgetItem(QStringList("A (type 1)"),
ItemType1));
w.addTopLevelItem(new QTreeWidgetItem(QStringList("B (type 1)"),
ItemType1));
w.addTopLevelItem(new QTreeWidgetItem(QStringList("C (type 2)"),
ItemType2));
w.addTopLevelItem(new QTreeWidgetItem(QStringList("D (type 2)"),
ItemType2));
app.exec();
return 0;
}
#include <QApplication>
#include <QMenu>
#include <QMouseEvent>
#include <QTreeWidget>
#include <QTreeWidgetItem>
// Qt documentation states that user types should begin at this value.
static const int ItemType1 = QTreeWidgetItem::UserType;
static const int ItemType2 = QTreeWidgetItem::UserType + 1;
class MyTreeWidget : public QTreeWidget
{
Q_OBJECT;
public:
MyTreeWidget()
{
setContextMenuPolicy(Qt::CustomContextMenu);
connect(this,
SIGNAL(customContextMenuRequested(const QPoint&)),
SLOT(onCustomContextMenuRequested(const QPoint&)));
}
private slots:
void onCustomContextMenuRequested(const QPoint& pos) {
printf("hi\n");
QTreeWidgetItem* item = itemAt(pos);
if (item) {
// Note: We must map the point to global from the viewport to
// account for the header.
showContextMenu(item, viewport()->mapToGlobal(pos));
}
}
void showContextMenu(QTreeWidgetItem* item, const QPoint& globalPos) {
QMenu menu;
switch (item->type()) {
case ItemType1:
menu.addAction("This is a type 1");
break;
case ItemType2:
menu.addAction("This is a type 2");
break;
}
menu.exec(globalPos);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment