0

I have declared an int function in mainwindow.h

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
    int port();

furthermore I declared this function in the appendant mainwindow.cpp file.

int MainWindow::port()
{
    int port_int;
    QString port_ei;

    if(ui->portInput->text() == 0)
    {
        port_ei = "6008";
        ui->textIncome->setPlainText(port_ei);
        port_int = port_ei.toInt();
    }
    else
    {
        port_ei = ui->portInput->text();
        ui->textIncome->setPlainText(port_ei);
        port_int = port_ei.toInt();
    }

    return port_int;
}

now i want my server (in the myserver.cpp file) to listen to that port.

MyServer::MyServer(QObject *parent) :
    QObject(parent)
{
    server = new QTcpServer(this);
    connect(server,SIGNAL(newConnection()),this,SLOT(newConnection()));

    int port_out =  MainWindow::port();

    if(!server->listen(QHostAddress::Any,port_out))
    {

        qDebug() << "Server could not start.";

    }
    else
    {
        qDebug() << "Server started.";
    }
}

but qt tells me that i made an illegal request on a not static function (on the int port_out = MainWindow::port(); line). how to solve that? and is there a better way to do this, if you got two seperate .cpp and .h files (besides the main.cpp). yes i included "mainwindow.h" and "myserver.h" in both cpp files.

1 Answer 1

1

MainWindow::port(); is a static function call. But port function is not static, it needs to be called like main_window->port() where main_windowis a pointer to a MainWindow object.

Sign up to request clarification or add additional context in comments.

5 Comments

how can i create a main_window pointer to MainWindow? *main_window = MainWindow ?
@beary: No. Take one step back. Which MainWindow? If your app only has one, use the appropriate qApp function
@beary: This is very general question. Are you not familiar with C++ at all? May be you should read some tutorials of books. Usually in Qt an object of main window class is created in main() function. Inside main window constructor and class member functions you have a pointer to MainWindow that can be referred to using this keyword. You can pass this pointer to MyServer constructor, for example.
@MSalters: using qApp in such a simple case is bad practice. The pointer should be passed manually. Dependency injection is better than singleton.
@Riateche: Matter of opinion. Passing around a pointer to a singleton is definitely not better than a straightforward singleton. Furthermore, it is always a good idea to stick with local custom. In the Qt case, that custom is the singleton qApp

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.