c++qtqt5subclass

How to subclass in Qt?


I'd like to subclass QListWidgetItem, but I don't get what I'm doing wrong. I subclassed QListWidget without any trouble using the same principles.

This is my header file :

#ifndef LSPROLISTITEM_H
#define LSPROLISTITEM_H

#include <QObject>
#include <QListWidgetItem>

class LsproListItem : public QListWidgetItem
{
    Q_OBJECT
public:
    explicit LsproListItem(QString &text, QObject *parent = 0);
signals:
public slots:
};

#endif // LSPROLISTITEM_H

and this is my cpp file :

#include "lsprolistitem.h"
#include <QListWidgetItem>

LsproListItem::LsproListItem(QString & text, QObject *parent) :
    QListWidgetItem(text, parent)
{
}

I don't get the argument from my custom constructor, to create an object based on QListWidgetItem.. I try to create is this way :

LsproListItem *simpleText = new LsproListItem("Lorem ipsum");

But this fails with :

appcms.cpp: error : no matching constructor for initialization of 'LsproListItem'
    LsproListItem *simpleText = new LsproListItem("Lorem ipsum");
                                    ^             ~~~~~~~~~~~~~

lsprolistitem.h:7: candidate constructor (the implicit copy constructor) not viable: no known conversion from 'const char [12]' to 'const LsproListItem' for 1st argument
class LsproListItem : public QListWidgetItem
      ^
lsprolistitem.h:: candidate constructor not viable: no known conversion from 'const char [12]' to 'QString &' for 1st argument
    explicit LsproListItem(QString &text, QObject *parent = 0);
             ^

Solution

  • Quick solution(not the best): don't use reference:

    public:
        explicit LsproListItem(QString text, QObject *parent = 0);
        //...
        LsproListItem::LsproListItem(QString text, QObject *parent) :
    

    Or

    public:
        explicit LsproListItem( const QString &text, QObject *parent = 0);
        //...
        LsproListItem::LsproListItem( const QString &text, QObject *parent) :
    

    But there is another mistake. Remove Q_OBJECT macro because QListWidgetItem is not a QObject subclass and you can't use here signal and slots.

    To prove: https://doc.qt.io/qt-5/qlistwidgetitem.html