QT开发之QListWidget控件增加右键菜单功能

在QListWidget的item上单击右键弹出菜单,

1、添加

 

2、设置QListWidget属性

3、不带图标的快捷菜单

添加信号和槽,这样在QListWidget中右键单击会弹出菜单了,菜单中的执行槽函数1、槽函数2自己定义,

void 类::on_listWidget_customContextMenuRequested(const QPoint &pos)
{
    QListWidgetItem* curItem = ui->listWidget->itemAt( pos );
    if( curItem == NULL )
        return;

    QMenu *popMenu = new QMenu( this );
    QAction *Menu1 = new QAction(tr("1111"), this);
    QAction *Menu2 = new QAction(tr("2222"), this);
    QAction *Menu3 = new QAction(tr("3333"), this);
    QAction *Menu4 = new QAction(tr("4444"), this);

    popMenu->addAction( Menu1 );
    popMenu->addAction( Menu2 );
    popMenu->addAction( Menu3 );
    popMenu->addAction( Menu4 );

    connect( Menu1, SIGNAL(triggered() ), this, SLOT( 槽函数1()) );
    connect( Menu2, SIGNAL(triggered() ), this, SLOT( 槽函数2()));
    connect( Menu3, SIGNAL(triggered() ), this, SLOT( 槽函数3()) );
    connect( Menu4, SIGNAL(triggered() ), this, SLOT( 槽函数4()));



    popMenu->exec( QCursor::pos() );
}

4、带图标的快捷菜单

    QIcon icon1 = QIcon(":/2.ico");  
    QIcon icon2 = QIcon(":/7.png");  
    QIcon icon3 = QIcon(":/4.png");  
    QIcon icon4 = QIcon(":/10.png");  
    QMenu *popMenu = new QMenu(ui->listWidget);


    QAction *Menu1 = popMenu->addAction(icon1,"111");
    QAction *Menu2 = popMenu->addAction(icon2,"222");
    QAction *Menu3 = popMenu->addAction(icon3,"333");
    QAction *Menu4 = popMenu->addAction(icon4,"444");

    connect(Menu1, SIGNAL(triggered(bool)), this, SLOT(槽函数1()));
    connect(Menu2, SIGNAL(triggered(bool)), this, SLOT(槽函数2()));
    connect(Menu3, SIGNAL(triggered(bool)), this, SLOT(槽函数3()));
    connect(Menu4, SIGNAL(triggered(bool)), this, SLOT(槽函数4()));
    
    
    popMenu->exec(QCursor::pos());//在当前鼠标位置显示

    //不能带删除

 

  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值