Created
October 17, 2012 15:48
-
-
Save jmk/3906292 to your computer and use it in GitHub Desktop.
Example of showing different context menu for items in a QTreeWidget
This file contains 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 "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; | |
} |
This file contains 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 <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
Спасибо пригодилось.