Question

I have a list of strings during run time.

Any one help me to display these strings in QWidget. When I right click that string I need to have a option show index that will show index of that string in QMessageBox.

If it is possible means give some technical guidance.

Thank you.

Was it helpful?

Solution

OK, so let us start with the design for your use case...

  • I would recommend using a QListWidget for a list. Each string could be a separate item.

  • You could show a popup for right click, but if it only has the show index action, it does not really make that much sense on its own. You could just show the messagebox with that index right away.

I would write something like this below:

MyClass::MyClass(QObject *parent)
    : QObject(parent)
    , m_listWidget(new QListWidget(this))
{
    QStringList myStringList = QStringList() << "foo" << "bar" << "baz";
    m_listWidget->addItems(myStringList);

    // Set up your action with the popup for right click if needed
    // and connect to the "triggered" signal of the particular action

    connect(listWidget, SIGNAL(itemClicked(QListWidgetItem * item)), SLOT(showMessageBox(QListWidgetItem * item)));

   ...

}

void MyClass::showMessageBox(QListWidgetItem * item)
{
    Q_UNUSED(item)
    QMessageBox messageBox;
    messageBox.setText(m_listWidget->currentRow());
    messageBox.exec();
}

If you have more actions for the right click, you could use a popup dialog, yes, with several actions placed onto, but so far, that does not seem to be the use case in here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top