I created a button and a textbrowser via gui drag&drop. the ui is created in the mainwindow.cpp as well as the click-button-function. There is a main.cpp but thats irrelevant cause the program shall not start until the startbutton is clicked.
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "myserver.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_startButton_clicked()
{
MyServer mServer;
}
This is all fine so far, the problem is in the myServer.cpp where I want to write something into the textBrowser via ui->textBrowser->append("hello hello");
. but the myServer.cpp class doesn't "know" the ui. "ui" not declared identifier
#include "myserver.h"
#include "mainwindow.h"
MyServer::MyServer(QObject *parent) :
QObject(parent)
{
}
void MyServer::newConnection()
{
server = new QTcpServer(this);
connect(server,SIGNAL(newConnection()),this,SLOT(newConnection()));
int ports = MainWindow::port();
if(!server->listen(QHostAddress::Any,ports))
{
}
else
{
//here is the problem
ui->textBrowser->append("hallo hallo");
}
}
normaly i would create a new (for example)
MainWindow test;
and call functions via this test.function();
but this does not work here?
First of all, when you create the MyServer object in the MainWindow::on_StartButtonClicked function, the object needs to be created dynamically, else it will go out of scope and get deleted, but perhaps you're just showing this, rather than its declaration in the MainWindow header.
As to your question, your UI is connected to the MainWindow, so use Qt's signals and slots to connect a signal from the MyServer object to the MainWindow and send it the text to be displayed. Then the MainWindow can add it to the textBrowser. Something like this: -
void MainWindow::on_startButton_clicked()
{
MyServer* mServer = new MyServer;
connect(mServer SIGNAL(updateUI(const QString)), this, SLOT(AppendToBrowser(const QString)));
}
Then instead of calling ui->textBrowser->append("hallo hallo"); in newConnection, emit the signal: -
emit updateUI("hallo hallo");
In MainWindow, you'd have the function AppendToBrowser: -
void MainWindow::AppendToBrowser(const QString text)
{
ui->textBrowser->append(text);
}
Alternatively, you could pass a pointer of the UI object to the MyServer and call it from there, but the signals and slots method is much cleaner.
=========== Edited for headers, in response to comments ======================
//Skeleton My Server header
class MyServer : public QObject
{
QOBJECT
signals:
void updateUI(const QString text);
};
// Skeleton MainWindow header
class MainWindow : public QMainWindow
{
private slots:
void AppendToBrowser(const QString text);
};