Created
October 17, 2012 16:18
-
-
Save jmk/3906464 to your computer and use it in GitHub Desktop.
Example of showing different context menu for items in a QTreeWidget (with QItemDelegate)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <QApplication> | |
#include <QItemDelegate> | |
#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 | |
{ | |
public: | |
// Re-declare as public. | |
QTreeWidgetItem* itemFromIndex(const QModelIndex& index) const; | |
}; | |
class MyItemDelegate : public QItemDelegate | |
{ | |
public: | |
MyItemDelegate(MyTreeWidget* treeWidget) : _treeWidget(treeWidget) | |
{ | |
// Do nothing. | |
} | |
// QAbstractItemDelegate override | |
virtual bool editorEvent( | |
QEvent* event, | |
QAbstractItemModel* model, | |
const QStyleOptionViewItem& option, | |
const QModelIndex& index ) | |
{ | |
QMouseEvent* mouseEvent = NULL; | |
if (event->type() == QEvent::MouseButtonPress) { | |
// This is only safe because we've checked the type first. | |
mouseEvent = static_cast<QMouseEvent*>(event); | |
} | |
if (mouseEvent and mouseEvent->button() == Qt::RightButton) { | |
QTreeWidgetItem* item = _treeWidget->itemAt(mouseEvent->pos()); | |
showContextMenu(item, mouseEvent->globalPos()); | |
// Return true to indicate that we have handled the event. | |
// Note: This means that we won't get any default behavior! | |
return true; | |
} | |
return QAbstractItemDelegate::editorEvent( | |
event, model, option, index); | |
} | |
private: | |
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); | |
} | |
private: | |
MyTreeWidget* _treeWidget; | |
}; | |
int main(int argc, char** argv) | |
{ | |
QApplication app(argc, argv); | |
MyTreeWidget w; | |
MyItemDelegate d(&w); | |
w.setItemDelegate(&d); | |
// 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)); | |
w.show(); | |
app.exec(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment