Question

I had this very simple server app, that worked perfect in a console. Now I switched to gui and made a new project, with nearly everything just as in the console project. One of the diffrences is the way of displaying my output. Instead of qDebug() << "Hello abc"; I now have to use ui->textBrowser->append("Hello abc");. This ui can only be called in the mainwindow.cpp.

#include "mainwindow.h"
#include "myserver.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::AppendToBrowser(const QString text)
 {
     ui->textBrowser->append(text);
 }

void MainWindow::on_startButton_clicked()
{
    MyServer* mServer = new MyServer;
    connect(mServer, SIGNAL(updateUI(const QString)), this, SLOT(AppendToBrowser(const QString)));
}

In the MyServer.cpp i have to use the connect function (see above) and emit the signal updateUI to the mainwindow.cpp.

#include "myserver.h"
#include "mainwindow.h"

MyServer::MyServer(QObject *parent) :
    QObject(parent)
{
    server = new QTcpServer(this);

    connect(server,SIGNAL(newConnection()), this, SLOT(newConnection()));

    if(!server->listen(QHostAddress::Any,1234))
    {
        emit updateUI("Server Error");
    }
    else
    {
        emit updateUI("Server started");
    }
}

void MyServer::newConnection()
{
    QTcpSocket *socket = server->nextPendingConnection();

    socket->write("Hello client!");
    socket->flush();

    socket->waitForBytesWritten(3000);

    socket->close();

    emit updateUI("Socket closed");
}

Here comes the problem : My textbrowser does ONLY display the last emit-command "Socket closed". I debug the program, hit the startbutton (that starts the server and connects the signal(updateUI) with the slot(appendToBrowser)) and connect to the programm via telnet. The program works fine so far that I see "hello client" and the quit on telnet but still, there is only the last emit output coming through "Socked Closed". In the very first moment I thought that my emits may override each other, but thats not possible cause a "Server started" or "Server Error" should be seen just after I click the startButton.

Any ideas how to solve this? I am working with c++ and qt for about 3 weeks now and I must admit that I get quite confused very fast so I hope you guys can understand my problem! thanks so far.

Was it helpful?

Solution

well it's pretty normal, if you make your connection in MyServer's constructor, you haven't connected it's signal to the mainwindow yet, so it won't display aynthing.

A basic fix would be to move the connection code (at least the if/else part) into a method, and call that method after connecting things together in your MainWindow::on_startButton_clicked() slot...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top