Search code examples
qtc++11qt5qlistwidgetqaction

How to add a QAction to a QListWidget


I have the following code:

roslaserscandoialog.h

public:
    explicit ROSLaserScanDialog(QWidget *parent = nullptr);
    ~ROSLaserScanDialog();
    QListWidgetItem *createItemFromAction(const QAction* action);

private slots:
    void on_listWidget_itemClicked(QListWidgetItem *item);

private:
    Ui::ROSLaserScanDialog *ui;
    QAction *mAddMsgs;
    QAction *mDeleteMsgs;

roslaserscandoialog.cpp

ROSLaserScanDialog::ROSLaserScanDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::ROSLaserScanDialog)
{
    ui->setupUi(this);
    connect(ui->listWidget,SIGNAL(on_listWidget_itemClicked(QListWidgetItem*)),this,SLOT(createItemFromAction(QListWidgetItem*)));

}


QListWidgetItem *ROSLaserScanDialog::createItemFromAction(const QAction *action)
{
    Q_ASSERT( action );
    QListWidgetItem *mAddMsgs = new QListWidgetItem();
    mAddMsgs->setText( action->text() );
    mAddMsgs->setToolTip( action->toolTip() );
    mAddMsgs->setIcon( action->icon() );
    // ...
    return mAddMsgs;
}

void ROSLaserScanDialog::on_listWidget_itemClicked(QListWidgetItem *item)
{
    mAddMsgs = new QAction(QIcon(":ros.png"), tr("Add New Message"), this);
    mDeleteMsgs = new QAction(QIcon(":remove_item.png"), tr("Remove Message"), this);
}

What I have done so far:

I came across this post and also this one. Very useful as I set up my project in a very similar way, but nothing happens when I try to click on the QListWidget.

I know that in order to trigger the action I have to go to the slot called itemClicked as I did on the above code provided. On the official documentation I was trying to apply what is advised but I don't know why nothing happens.

Please point to the right direction for solving this problem.


Solution

  • Look at console output, there should a warning about connect failing. If you look at your code, the reason should be pretty obvious. Consider

    SLOT(createItemFromAction(QListWidgetItem*))
    

    versus your method which isn't even a slot

    QListWidgetItem *createItemFromAction(const QAction* action);
    

    See the difference?


    And then you have this slot:

    void on_listWidget_itemClicked(QListWidgetItem *item);
    

    which you are trying to use as a signal

    SIGNAL(on_listWidget_itemClicked(QListWidgetItem*))
    

    That obviously won't work.


    It's a bit unclear what you want to happen when an item is clicked, but maybe you just should call createItemFromAction directly from the on_listWidget_itemClicked.

    Additionally, add debug print or use breakpoint to verify that the on_listWidget_itemClicked is actually called when you click an item. If not, then you are missing connecting the relevant signal from your list view, ie. ui->setupUi(this); does not have that connect (in other words you did not do the connection in the GUI Designer).