Can't derive from a QListWidgetItem so I can extend it's capabilities.



  • Hello!
    I am a QT beginner so my question is rather simple.
    Please let me paste in the code first and then I'll describe what my problem is.
    So this is my mainwindow.cpp:

    #include "mainwindow.h"
    #include "ui_mainwindow.h"
    
    MainWindow::MainWindow(QWidget *parent) :
        QMainWindow(parent),
        ui(new Ui::MainWindow)
    {
        ui->setupUi(this);
        ui->splitter->setStretchFactor(0, 3);
        ui->splitter->setStretchFactor(1, 7);
        TabSelect item("tab");
        ui->tabsList->addItem(item);
    }
    
    MainWindow::~MainWindow()
    {
        delete ui;
    }
    

    and this is my tabselect.h:

    #ifndef TABSELECT_H
    #define TABSELECT_H
    
    #include <QListWidgetItem>
    
    class TabSelect : public QListWidgetItem
    {
        Q_OBJECT
    public:
        std::string tabName;
        int participants;
        std::string leadingClub;
        TabSelect(std::string tabName);
        void update();
    };
    
    #endif // TABSELECT_H
    

    and tabselect.cpp:

    #include "tabselect.h"
    #include <string>
    
    TabSelect::TabSelect(std::string tabName)
    {
        this->tabName = tabName;
        this->participants = 0;
        this->leadingClub = "";
        this->update();
    }
    
    
    void TabSelect::update()
    {
        std::string content;
        content = "<b>tabName</b>\n";
        content +="<i>Uczestnicy: " + std::to_string(participants) + "</i>";
        content += "\n<i>Klub prowadzący: " + leadingClub + "</i>";
        this->QListWidgetItem::setText(QString::fromStdString(content));
    }
    
    

    So my problem is, I can not do this line:

    ui->tabsList->addItem(item);
    

    because QListWidget expects QListWidgetItem, not my derived class. Is there a way to make it work as I would like?


  • Lifetime Qt Champion

    Hi and welcome to devnet,

    There's no problem in using QListWidgetItem subclasses. Your current problem is that you are trying to pass an object of your TabSelect class, take a look again at the signature of the function, the item are allocated on the heap not on the stack.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.