Program-Me-Rev Program-Me-Rev - 4 years ago 124
C++ Question

error: could not convert ‘((const MyClass*)this)->MyClass::myLabel’ from ‘QLabel* const’ to ‘QLabel’

I'm trying to return a QLabel from a function, but I keep getting the error:

/media/root/5431214957EBF5D7/projects/c/qt/tools/plugandpaint/plugins/extrafilters/extrafiltersplugin.cpp:17: error: could not convert ‘((const ExtraFiltersPlugin*)this)->ExtraFiltersPlugin::retLabel’ from ‘QLabel* const’ to ‘QLabel’


^~~~~~~~


extrafiltersplugin.h

#ifndef EXTRAFILTERSPLUGIN_H
#define EXTRAFILTERSPLUGIN_H

#include <interfaces.h>

#include <QObject>
#include <QtPlugin>
#include <QImage>
#include <QLabel>

class ExtraFiltersPlugin :
public QObject,

public FilterInterface,
public RevViewsInterface
{
Q_OBJECT
Q_PLUGIN_METADATA(IID "org.qt-project.Qt.Examples.PlugAndPaint.FilterInterface" FILE "extrafilters.json")
Q_INTERFACES(FilterInterface RevViewsInterface)

public:
ExtraFiltersPlugin();

// RevInterface
QLabel label() const override;

private:
QLabel *retLabel;
};

#endif


extrafiltersplugin.cpp

#include <QtWidgets>

#include <stdlib.h>

#include "extrafiltersplugin.h"

ExtraFiltersPlugin::ExtraFiltersPlugin() {
retLabel = new QLabel();
retLabel->setFrameStyle(QFrame::Panel | QFrame::Sunken);
retLabel->setText("first line\nsecond line");
retLabel->setAlignment(Qt::AlignBottom | Qt::AlignRight);
}

QLabel ExtraFiltersPlugin::label() const
{
return retLabel;
}


What could it be that I'm doing wrong or missing? I'm a total C++/ Qt newbie, if this seems completely obvious.

Thank you all in advance.

Answer Source

You can't return a QLabel (or an instance of any QWidget derived class) by value as they can't be copied.

You need to change the signature of ExtraFiltersPlugin::label so that it returns either a pointer...

QLabel *ExtraFiltersPlugin::label () const
{
  return retLabel;
}

or a reference...

QLabel &ExtraFiltersPlugin::label () const
{
  return *retLabel;
}

Note that both of the above allow the caller to modify the referenced QLabel. If that's not needed (or desired) then the return type should be const QLabel * or const QLabel & respectively.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download