c++ - qt c 发出文本浏览器

标签 c++ qt emit

我有一个非常简单的服务器应用程序,在控制台中运行得很好。 现在我切换到 GUI 并创建了一个新项目,几乎所有内容都与控制台项目中一样。 差异之一是显示输出的方式。而不是qDebug() << "Hello abc";我现在必须使用ui->textBrowser->append("Hello abc"); 。 这个ui只能在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)));
}

在 MyServer.cpp 中,我必须使用 connect 函数(见上文)并向 mainwindow.cpp 发出 updateUI 信号。

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

问题来了:我的文本浏览器显示最后一个发出命令“套接字已关闭”。我调试程序,点击启动按钮(启动服务器并将信号(updateUI)与插槽(appendToBrowser)连接)并通过 telnet 连接到程序。 到目前为止,程序运行良好,我看到“hello client”和 telnet 上的退出,但仍然只有最后一个发出输出通过“Socked Closed”。 在第一时刻,我认为我的发出可能会相互覆盖,但这不可能,因为在我单击开始按钮后应该会看到“服务器已启动”或“服务器错误”。

有什么想法可以解决这个问题吗?我现在使用 c++ 和 qt 工作了大约 3 周,我必须承认我很快就变得很困惑,所以我希望你们能理解我的问题!到目前为止谢谢。

最佳答案

这很正常,如果你在 MyServer 的构造函数中进行连接,你还没有将它的信号连接到主窗口,所以它不会显示任何内容。

一个基本的修复方法是将连接代码(至少是 if/else 部分)移动到一个方法中,并在 MainWindow::on_startButton_clicked() 槽中将事物连接在一起后调用该方法...

关于c++ - qt c 发出文本浏览器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17468788/

相关文章:

c++ - C/C++如何复制结构?

c++ - 在 Linux ARM 上使用 libusb 的状态热敏打印机

c++ - QWidget继承自自定义QWidget

ruby - QtRuby 发射不起作用

python - 有什么好的 Python 程序集生成模块吗?

c++ - 控制台宽度;承担违约或成为……?

c++ - 如何实现一个轻量级的快速关联数组?

c++ - 编译 .cu 与 .cpp : Compiler errors even without any CUDA code

c++ - 在 Linux 上使用 QtWebkit 和 OpenSSL 部署 Qt 应用程序时出现问题

vue.js - VueJs 树递归元素发送给父级