我试图从一个函数返回一个 QLabel,但我一直收到错误:
/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;
}
我做错了什么或遗漏了什么?如果这看起来很明显的话,我完全是 C++/Qt 新手。
提前谢谢大家。
最佳答案
您不能按值返回 QLabel
(或任何 QWidget
派生类的实例),因为它们无法复制。
您需要更改 ExtraFiltersPlugin::label
的签名,以便它返回一个指针...
QLabel *ExtraFiltersPlugin::label () const
{
return retLabel;
}
或引用...
QLabel &ExtraFiltersPlugin::label () const
{
return *retLabel;
}
请注意,以上两者都允许调用者修改引用的QLabel
。如果不需要(或不需要),则返回类型应分别为 const QLabel *
或 const QLabel &
。
关于c++ - 错误 : could not convert ‘((const MyClass*)this)->MyClass::myLabel’ from ‘QLabel* const’ to ‘QLabel’ ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42050045/