Important: Please read the Qt Code of Conduct -

How to add images to a Listview in QML?

  • Hi all, i am new to Qml and now i am trying an application in which:when a button is pressed a list of images should be displayed in a QListView.

    What i had tried so far is:

    I had created a button in .qml file and when clicked on it the function call goes to .cpp file to display the listview with images.
    I was able to do it in .qml file itself but i am looking to display it by making a function call to .cpp.

    My code:

    .qml file

    Button {
    id: button1
    x: 79
    y: 299
    text: "Click here for listview"

        onClicked: {


    .cpp file:


    void Abcd::apple()
    QListWidget *listWidget = new QListWidget();
    listWidget->addItem(new QListWidgetItem(QIcon("c:/apple.jpg")));
    listWidget->addItem(new QListWidgetItem(QIcon("c:/ball.jpg")));
    listWidget->addItem(new QListWidgetItem(QIcon("c:/cat.jpg")));
    listWidget->addItem(new QListWidgetItem(QIcon("c:/dog.jpg")));

        QHBoxLayout *layout = new QHBoxLayout();
        QMainWindow w;


    From my code i was able to get the function call to the .cpp file when tried with some other samples....but when trying to display the image i was not able to do it..

    Anyone help me with this so that i can find the solution....


    [EDIT: code formatting, please wrap in @-tags, Volker]

  • Moderators

    Lots and lots of issues here.

    First, format your code nicely, using '@' tags and inserting new line after every or most ';'.

    Next, you are mixing QtWidgets and QML, which is not the usual course of things. If you want to add custom functionality to QML, you have to use relevant QDeclarative* classes.

    Another thing is, you are creating QMainWindow on a stack, which means that this object will be deleted when the scope ends. in your case, that's the closing bracket ('}').

    Also, void Abcd::apple() - is this method a slot, or declared with Q_INVOKABLE? OTherwise, you will not be able to invoke it from QML.

  • I will try what you have said sir if this works thanks a lot..:)

Log in to reply