Skip to content

Instantly share code, notes, and snippets.

@jmk
Created October 17, 2012 15:48
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save jmk/3906292 to your computer and use it in GitHub Desktop.
Save jmk/3906292 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);
}
};
@folax
Copy link

folax commented Jun 2, 2015

Спасибо пригодилось.

@ganeshkbhat
Copy link

@sinitcin The action is coming disabled. Whats the method to enable to the action capture?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment