程序目的是想要在一个tree列表中点击右键,如果在Item上面,则有“车辆轨迹回放” “取消轨迹回放”选项,在其余空白处,则只有“发送消息提示至车辆”。请各位大侠帮帮忙
//myTreeWidget.h
#include <QtGui/QMainWindow>
#include <qtreewidget.h>
#include <qevent.h>
#include <qmenu.h>
class myTreeWidget : public QTreeWidget
{
Q_OBJECT
public:
myTreeWidget(QWidget *parent = 0);
~myTreeWidget();
void createActions();
protected:
void contextMenuEvent ( QContextMenuEvent * event );
private:
QAction *sendInfoHintAction;
QAction *pathReplayAction;
QAction *canncelPathReplayAction;
QMenu *popMenu;
};
//myTreeWidget.cpp
#include "myTreeWidget.h"
myTreeWidget::myTreeWidget(QWidget *parent)
: QTreeWidget(parent)
{
createActions();
popMenu = new QMenu(this);
}
myTreeWidget::~myTreeWidget()
{
}
void myTreeWidget::contextMenuEvent ( QContextMenuEvent * event )
{
popMenu->addAction(sendInfoHintAction);
QTreeWidgetItem *item = NULL;
QPoint point = QCursor::pos();//得到鼠标的位置,全局坐标
point = mapFromGlobal(point);//mapFromGlobal将全局坐标转化成窗口坐标
item = this->itemAt(point);//为什么这里返回的都是NULL?
if(item != NULL)
{
popMenu->addAction(pathReplayAction);
popMenu->addAction(canncelPathReplayAction);
}
popMenu->exec(QCursor::pos());//菜单出现的位置为当前鼠标的位置
event->accept();
}
void myTreeWidget::createActions()
{
sendInfoHintAction = new QAction(tr("发送信息提示"),this);
sendInfoHintAction->setStatusTip(tr("发送消息提示至车辆"));
pathReplayAction = new QAction(tr("车辆轨迹回放"),this);
pathReplayAction->setStatusTip(tr("获取车辆在某时间段的轨迹坐标"));
canncelPathReplayAction = new QAction(tr("取消轨迹回放"),this);
}
//main.cpp
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QApplication::addLibraryPath("./plugins");
QTextCodec::setCodecForLocale(QTextCodec::codecForName("GB2312"));
QTextCodec::setCodecForTr(QTextCodec::codecForName("GB2312"));
QTextCodec::setCodecForCStrings(QTextCodec::codecForName("GB2312"));
myTreeWidget *treeWidget = new myTreeWidget;
treeWidget->setRootIsDecorated(false);
QStringList list;
list << "123";
QTreeWidgetItem *item = new QTreeWidgetItem(list);
treeWidget->addTopLevelItem(item);
treeWidget->show();
return a.exec();
}
------解决方案--------------------
------解决方案--------------------