天天看點

QT開發之QListWidget控件增加右鍵菜單功能

在QListWidget的item上單擊右鍵彈出菜單,

1、添加

QT開發之QListWidget控件增加右鍵菜單功能

2、設定QListWidget屬性

QT開發之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());//在目前滑鼠位置顯示

    //不能帶删除