C++ 在Qt5中创建继承类的最简单方法是什么?
我是一个Qt新手,我所要做的就是创建一个自定义的C++ 在Qt5中创建继承类的最简单方法是什么?,c++,qt,class,inheritance,C++,Qt,Class,Inheritance,我是一个Qt新手,我所要做的就是创建一个自定义的QLineEdit类,并进行一些自定义(默认对齐和默认文本)。现在我正试图建立一个基类,只继承QWidget。这就是我所拥有的(我知道非常糟糕的代码): 用户文本(utxt.h): 我知道这确实是错误的,并且在utxt.cpp中的两个函数上不断出现“local function definition is likely”错误。有人能给我指一下正确的方向吗?我正在尝试创建一个自定义的QLineEdit,以将我的其他行编辑提升到。QLineEdit已经
QLineEdit
类,并进行一些自定义(默认对齐和默认文本)。现在我正试图建立一个基类,只继承QWidget
。这就是我所拥有的(我知道非常糟糕的代码):
用户文本(utxt.h):
我知道这确实是错误的,并且在utxt.cpp中的两个函数上不断出现“local function definition is likely”错误。有人能给我指一下正确的方向吗?我正在尝试创建一个自定义的
QLineEdit
,以将我的其他行编辑提升到。QLineEdit
已经有了可以设置的
LE:正如我所说的,这个功能不需要从QLineEdit
(或QWidget
)继承,但是如果你真的想这样做,你可以创建你的类,编写一个构造函数,它接受你想要的参数,并调用QLineEdit
,比如:
//in the header
//... i skipped the include guards and headers
class utxt : public QLineEdit
{
Q_OBJECT
public:
//you can provide default values for all the parameters or hard code it into the calls made from the constructor's definition
utxt(const QString& defaultText = "test text", Qt::Alignment align = Qt::AlignRight, QWidget *parent = 0);
};
//in the cpp
utxt::utxt(const QString& defaultText, Qt::Alignment alignement, QWidget *parent) : QLineEdit(parent)
{
//call setPlaceHolder with a parameter or hard-code the default
setPlaceholderText(defaultText);
//same with the default alignement
setAlignment(alignement);
}
看起来你也是一个C++新手。不能在构造函数中定义函数。在尝试使用Qt之前,应该先从简单的项目开始。如果你想创建一个“自定义QLineEdit”,那么首先从QLineEdit继承。哦,天哪,我是个白痴!我已经习惯了源文件中的类定义,就像在C#中一样,我只是假设它是一个类定义。我将函数放在构造函数之外,错误被清除。谢谢但有一个问题。。。如果我从QLineEdit继承,我是否也从QWidget继承?因为我想我只从QLineEdit继承了一次,而SetGeometry等函数都不可用。我必须同时继承这两个吗?不,你不能同时继承QWidget和QLineEdit(因为两者都间接继承QObject,并且你的类层次结构中不能有两次QObject),无论如何,请告诉我们更多关于你试图做什么的信息,因为你描述的功能可以在不继承QLineEdit的情况下完成。
#include "utxt.h"
utxt::utxt(QWidget *parent) :
QWidget(parent)
{
QString utxt::text()
{
return this->displayText;
}
void utxt::setAlignment(Qt::Alignment align)
{
this->alignment = align;
}
}
//in the header
//... i skipped the include guards and headers
class utxt : public QLineEdit
{
Q_OBJECT
public:
//you can provide default values for all the parameters or hard code it into the calls made from the constructor's definition
utxt(const QString& defaultText = "test text", Qt::Alignment align = Qt::AlignRight, QWidget *parent = 0);
};
//in the cpp
utxt::utxt(const QString& defaultText, Qt::Alignment alignement, QWidget *parent) : QLineEdit(parent)
{
//call setPlaceHolder with a parameter or hard-code the default
setPlaceholderText(defaultText);
//same with the default alignement
setAlignment(alignement);
}