[SOLVED] Console application with thread: It is not closed



  • I'm coding a console application that runs a QThread for connections and at same time, waits for user inputs by keyboard.

    My problem is that then of read what user's write, I send a signal to close the application and nothing happens. Is the first console appliation using Qt and I'm not sure if I'm following what Qt waits. Here is the code:

    @int main(int argc, char *argv[])
    {
    QCoreApplication app(argc, argv);
    CommandLineApp cmd;

    QObject::connect(&cmd, SIGNAL(quitApp()), &app, SLOT(quit()));
    
    cmd.exec();
    
    return app.exec();
    

    }@

    CommandLineApp.h (Server is a QTcpServer that has a QThread inside):
    @#ifndef CommandLineApp_H
    #define CommandLineApp_H

    #include <QObject>
    #include "Server.h"
    #include <iostream>

    using namespace std;

    class CommandLineApp : public QObject
    {
    Q_OBJECT

    signals:
        void quitApp();
    
    public:
        CommandLineApp(QObject *parent = 0);
        void exec&#40;&#41;;
    
    private:
        Server server;
    

    };

    #endif@

    CommandLineApp.cpp:
    @CommandLineApp::CommandLineApp(QObject *parent) : QObject(parent)
    {
    server.listen(QHostAddress::LocalHost,5555);
    }

    void CommandLineApp::exec()
    {
    string option;

    QTextStream cout(stdout&#41;;
    QTextStream cin(stdin);
    
    cout<<"Set option (help for Help, quit for Quit): ";
    cout.flush();
    cin>>option;
    
    server.close();
    
    emit quitApp();
    

    }
    @


  • Moderators

    You emit quitApp() before QCoreApplication enters it's event loop: that is, before signals and slots (and the whole Qt Meta Ojbect System) is able to work.



  • Arg! Thanks a lot!!

    Sometimes we are looking for complex problems and the problem is basic!

    Shoddy solution: add a timer with singleShot! :)


  • Moderators

    You are welcome.

    Solution good enough if it works :) Qt is more oriented towards GUI stuff (obviously), command line apps are sometimes a bit tricky.



  • Hi, IMO,

    @
    return app.exec();
    @

    can be simply replaced with

    @
    return 0;
    @

    As the event loop make non-sense in such case.



  • Thanks 1+1=2, it also works I've decided to to it to get more clear code.

    Mark the topic as solved!! :)


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.