从Qt调用C++函数(插槽不起作用)

Calling a C++ function from Qt (slot does not work)

本文关键字:插槽 不起作用 函数 Qt 调用 C++      更新时间:2023-10-16

我用c++编写了一个客户端-服务器程序。现在我必须使用QT来创建界面。我已经创建了一个登录界面。当我单击登录按钮时,它应该调用sendmessage函数,该函数将用户名和密码发送到服务器(也用C++编写),服务器会对其进行验证,并将true或false发送回sendmessage函数。如果是真的,该窗口应该关闭并打开一个新窗口,否则它应该再次显示登录窗口,以便用户可以重试。现在,如何实现这一点,循环,以及是否可以使用信号和槽来调用c++函数。关于如何进行,一些想法会很好

以下是我的代码:

 Log::Log(QWidget *parent)
:QWidget(parent){
    QGridLayout *grid = new QGridLayout(this);
    grid->setSpacing(20);
    QLabel *username = new QLabel("Username", this);
    grid->addWidget(username, 0, 0, 1, 1);
    edt1 = new QLineEdit(this);
    grid->addWidget(edt1, 0, 1, 1, 3);
    QLabel *password = new QLabel("Password", this);
    grid->addWidget(password, 1, 0, 1, 1);
    edt2 = new QLineEdit(this);
    grid->addWidget(edt2, 1, 1, 1, 3);
    QPushButton *login = new QPushButton("Login", this);
    grid->addWidget(login, 3, 4, 1, 1);
    setLayout(grid);
    connect(login, SIGNAL(clicked()), this, SLOT(send_message()));
}
 //Other code

bool send_message(){
     buff = edt1->text() + edt2->text();
    write(socket, buff_send, 256); //Sends to the server
    read(socket, buff_recv, 256); //Gets the reply from the server
    if(buff_recv==true){
          loginwin.close();
          return true}
    else return false;
   }

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    Login logwin;
    logwin.move(300, 300);
    logwin.setWindowTitle("LOGIN");
    window.show();
}

我知道这是完全错误的。但我希望你明白我想说的,并给出一些如何做到这一点的技巧。

只需在头文件中注册一个Qt插槽。

class Log {
  ...
  Q_SLOTS:
    void sendMessage ();
}

并在实现中实现时隙,例如通过:

Log::sendMessage() {
  send_message();
}

不要忘记将connect语句更改为仅sendMessage()函数,而不是send_message函数。