来自另一个类的Qt c ++ GUI调用

时间:2013-07-03 13:59:21

标签: c++ qt class user-interface undeclared-identifier

我通过gui drag& drop创建了一个按钮和一个文本浏览器。 ui是在mainwindow.cpp中创建的,也是在click-button-function中创建的。有一个main.cpp,但这是无关紧要的,因为程序在单击startbutton之前不会启动。

#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;
}

到目前为止一切都很好,问题出在myServer.cpp中,我想通过ui->textBrowser->append("hello hello");在textBrowser中写一些东西。但myServer.cpp类并不“知道”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我会创建一个新的(例如) MainWindow test;并通过此test.function();调用函数 但这在这里不起作用?

2 个答案:

答案 0 :(得分:4)

首先,当你在MainWindow :: on_StartButtonClicked函数中创建MyServer对象时,需要动态创建对象,否则它将超出范围并被删除,但也许你只是展示了这个,而不是比它在MainWindow标题中的声明。

关于你的问题,你的UI连接到MainWindow,所以使用Qt的信号和插槽将MyServer对象的信号连接到MainWindow,并向其发送要显示的文本。然后MainWindow可以将它添加到textBrowser。这样的事情: -

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

然后,而不是调用ui-> textBrowser-> append(“hallo hallo”);在newConnection中,发出信号: -

emit updateUI("hallo hallo");

在MainWindow中,您将拥有AppendToBrowser函数: -

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

或者,您可以将UI对象的指针传递给MyServer并从那里调用它,但信号和插槽方法更清晰。

===========编辑标题,以回应评论======================

// Skeleton My Server标题

class MyServer : public QObject
{
    QOBJECT

    signals:
         void updateUI(const QString text);
};

// Skeleton MainWindow标题

class MainWindow : public QMainWindow
{
    private slots:
        void AppendToBrowser(const QString text);
};

答案 1 :(得分:1)

您有两种选择:
1)将信号编码到MyServer类中,该信号将更新gui所需的数据和插槽传递到MainWindow类,该类执行更新ui并将信号与插槽连接的工作。

或 2)你可以将一个指向MainWindow的指针传递给MyServer(也许它有意义成为父节点)并使用该指针调用你编码到MainWindow中的公共功能,并用你需要的数据更新ui。

LE:两个问题:
1)我看到你在堆栈中将MyServer实例创建到* on_startButton_clicked *中,如果该对象被快速销毁,这可能是一个问题,所以你应该确保只要你需要它就保持活着,这样就可以了可以做它的工作。
2)这行应该做什么: connect(服务器,SIGNAL(newConnection()),这个,SLOT(newConnection())); 即使你有一个newConnection信号,为什么要连接那个进入你连接的插槽,以及第一次连接的时间,执行插槽和建立连接,所以检查你在那里做了什么......