Qt右击菜单栏实现

Qt右击菜单栏实现

2016年02月17日 09:18:16 vaychouzww 阅读数 972

1.以treeview控件为例,首先,设置treeview的右击属性,

   ui->treeView_2->setContextMenuPolicy(Qt::CustomContextMenu);
2.创建treeview右击菜单槽函数,如:
 
void MainWindow::on_treeView_2_customContextMenuRequested(const QPoint &pos)
{
    QAction* common = nullptr;
    common = new QAction(QIcon(":/TreeIcon/TreeIcon/refresh.png"), tr("刷新列表"), this);
    QAction* cc_1 = nullptr;
    cc_1 = new QAction(QIcon(":/TreeIcon/TreeIcon/changelib.png"), tr("修改设备"), this);
    QAction* cc_2 = nullptr;
    cc_2 = new QAction(QIcon(":/TreeIcon/TreeIcon/property.png"), tr("设备属性"), this);
 
 
    QMenu *menu = new QMenu(this);
    menu->addAction(common);
    menu->addAction(cc_1);
    menu->addAction(cc_2);
 
    connect(common, &QAction::triggered, this, &MainWindow::UpdateDevList); //每个Action信号相应一个槽函数
    connect(cc_1, &QAction::triggered, this, &MainWindow::changedev);
    connect(cc_2, &QAction::triggered, this, &MainWindow::showdevsta);
    menu->setStyleSheet("QMenu{background-color:rgb(255,255,255);color:rgb(35, 103, 174);font:10pt ""Microsoft YaHei"";}"
    "QMenu::item:selected{background-color:#CCDAE7;}"
    "QMenu::item:disabled{color:#BFBFBF;}");
 
 
    QModelIndex index = ui->treeView_2->indexAt(pos);
    if(index.data().toString().isEmpty())
    {
 
        cc_1->setDisabled(true);
        cc_2->setDisabled(true);
        menu->exec(QCursor::pos());
    }else if(!index.parent().isValid())
    {
        cc_1->setDisabled(true);
        cc_2->setDisabled(true);
        menu->exec(QCursor::pos());
    }else if(index.parent().isValid())
    {
 
        /*QModelIndex cur_p = index.parent();
        int selectrow_p = cur_p.row();
        int selectrow_c = index.row();
        QStandardItemModel* model = static_cast(ui->treeView->model());
        QStandardItem* item = model->item(selectrow_p,0)->child(selectrow_c,0);
        libm_storied = item->accessibleText().toStdString();
        QList::iterator it2;
        for(it2 = facewin.begin();it2 != facewin.end();++it2)
        {
            if(QString::fromStdString(libm_storied).toInt() == (*it2)->storeid)
            {
                libm_confide = QString::number((*it2)->confide).toStdString();
                break;
            }
        }*/
        menu->exec(QCursor::pos());
    }
}

你可能感兴趣的:(Qt,Qt右击菜单栏实现)