简体   繁体   English

无法使QSignalMapper正常工作

[英]Can't get QSignalMapper to work

I'm making an application using the C++ Qt Framework. 我正在使用C ++ Qt Framework制作应用程序。 The problem I have at the moment is similar to submitting a form. 我目前遇到的问题类似于提交表单。 I need to add a Client to the system. 我需要将客户端添加到系统中。 So when you click the "Add Client" button, it needs to submit the text from a QLineEdit and a QDate from a QDateEdit to a function. 因此,当您单击“添加客户端”按钮时,它需要将QLineEdit中的文本和QDateEdit中的QDate提交给函数。

The more I have researched, the more it seems I have to use a QSingalMapper, but I cannot seem to get it to work at all. 我研究的越多,似乎就越需要使用QSingalMapper,但我似乎根本无法使用它。

Here's a snippet of the code I tried to use first. 这是我首先尝试使用的代码片段。 I have a Client data structure with the Name and Joining Date that needs to be submitted. 我有一个带有名称和加入日期的客户数据结构,需要提交。 I can, however, also create the Client object and pass that through as a parameter insead if it's a better idea. 但是,我也可以创建Client对象,并将其作为参数insead传递给它(如果有更好的主意)。

 QObject::connect(addClientBtn, SIGNAL(clicked()), this, SLOT(addClient(clientName->text(), joiningDate->date())));

When I tried to use QSignalMapper, it kept telling me that I can't send a Client object because its not of type QString, Widget*, etc. 当我尝试使用QSignalMapper时,它一直告诉我无法发送Client对象,因为它的类型不是QString,Widget *等。

Is there maybe an easier way to do this that I've overlooked? 有没有一种更容易被我忽略的方法? Any help would be greatly appreciated. 任何帮助将不胜感激。

You do not need a QSignalMapper if I understand you correctly but its difficult to tell as you hardly posted any code. 如果我对您的理解正确,则不需要QSignalMapper ,但是由于您几乎没有张贴任何代码,所以它很难告诉您。 Expecially it is difficult because we have no idea what this is. 特别是很难,因为我们不知道this是什么。 But assuming it is a QDialog or QMainWindow , you have to do something along the following: 但是,假设它是QDialogQMainWindow ,则必须执行以下操作:

in the class definition .h 在类定义.h中

...
protected slots:
    void add_client();
...

in the class implementation .cpp 在类实现.cpp中

mydialogormainwindow::mydialogormainwindow(){

    QObject::connect(addClientBtn, SIGNAL(clicked()), this, SLOT(addClient()));
}

void mydialogormainwindow::add_client(){

    QString name = clientName->text();
    QDate date = joiningDate->date();
    ....
}

This is due to the signal-slot connection. 这是由于信号插槽连接。 The Signal sends out a signal including parameters which are sent to the slot. 信号发出一个信号,该信号包括已发送到插槽的参数。 The clicked signal has no parameters so it can't send anything along to the slot. 单击的信号没有参数,因此无法将任何东西发送到插槽。 But with the slot being defined in the same class, you can access the data there directly. 但是,由于插槽是在同一类中定义的,因此您可以直接在那里访问数据。

Note: This works only if your class is a derived QObject (which is the case for QDialog and QMainWindow ) and has the Q_OBJECT macro in its class definition. 注意:仅当您的类是派生的QObject (对于QDialogQMainWindow就是这种情况)并且在类定义中具有Q_OBJECT宏时,此方法才有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM