连接信号(Qstring)白色插槽(字符串)的2个不同类别

connect signal (Qstring) whit slot (String) of 2 different class

本文关键字:2个 同类 插槽 信号 Qstring 白色 连接 字符串      更新时间:2023-10-16

>i 有 2 个类:类 MaFentre 和 Code

代码.h :

class Code : public QObject {
public :

explicit  Code(Q3DScatter *scatter);
public slots:
std::vector<point> readingData(std::string inputFileName);
}

MaFenetre.h :

class MaFenetre : public QWidget
{  Q_OBJECT
public:
MaFenetre();
private:
QLineEdit *entry1;
}

代码.cpp :

std::vector<point> Code::readingData(std::string inputFileName){
// i read a file here
}

我在类 MaFenetre 的构造函数中创建 Code 类对象

Code *modifier = new Code(graph);

用于在插槽和信号之间建立连接

QObject::connect(entry1, SIGNAL(textChanged(QString)),modifier, SLOT(readingDara(std::string inputFileName)))

我知道参数必须是相同的类型,为此我尝试编码:

QObject::connect(entry, SIGNAL(textChanged(QString.toStdString)),modifier, SLOT(readingDara(std::string inputFileName)))

但它不起作用

您的信号和时隙参数不兼容。

您可以使用lambda函数执行此解决方法

Code *modifier = new Code();
MaFenetre * poMaFenetre = new MaFenetre();
connect(poMaFenetre->Entry(), &QLineEdit::textChanged,
[modifier](const QString & oText)
{
std::vector<int> data = modifier->readingData(oText.toStdString());
// Handle data here...
});

MaFenetre

class MaFenetre : public QWidget
{
Q_OBJECT
public:
MaFenetre() {entry1.reset(new QLineEdit());}
QLineEdit *Entry() {return entry1.data();}
private:
QScopedPointer<QLineEdit> entry1;
};

使用信号和插槽与调用函数和传递参数不同。

首先,信号和时隙必须具有相同的参数类型,这意味着它们必须使用相同的参数定义。在您的情况下,您必须更改插槽以适应可能的信号。另请注意,在槽调用的情况下,返回值是无用的,所以更好的方法是保持你按原样读取函数,将其移动到私有区域,并创建包装槽:

void Code::readingDataSlot(QString inputFileName)
{
std::vector<point> result = readingData( inputFileName.toStdString() );
// Do what ever you need with result vector
}

并将其连接到信号。

connect(entry1, SIGNAL(textChanged(QString)),modifier, SLOT(readingDataSlot(QString)));