我有一个服务器和客户端。我将把我的时钟句柄更改为新值,由客户端发送到服务器。我添加了下面的源代码。我的问题是在客户端将数据发送到服务器以将时钟句柄更改为新数据后,客户端连接到服务器在Server::startRead()方法中创建的gui会自动出现和消失。请问我的代码出了什么问题。
server.h
#ifndef SERVER_H
#define SERVER_H
#include <QtNetwork>
#include <QObject>
#include <QTcpServer>
#include <QTcpSocket>
class Server: public QObject
{
Q_OBJECT
public:
QString buf;
Server(QObject * parent = 0);
~Server();
public slots:
void acceptConnection();
void startRead();
QString getinfo();
private:
QTcpServer server;
QTcpSocket* client;
};
#endif // SERVER_H
服务器.cpp
#include <QGuiApplication>
#include "server.h"
#include <QDebug>
#include <iostream>
#include <QApplication>
#include "qlabel.h"
#include <QtGui>
Server::Server(QObject* parent): QObject(parent)
{
connect(&server, SIGNAL(newConnection()),
this, SLOT(acceptConnection()));
server.listen(QHostAddress::Any, 1234);
qDebug() << "connected";
}
Server::~Server()
{
server.close();
}
void Server::acceptConnection()
{
qDebug()<<"accept connection";
client = server.nextPendingConnection();
client->write("Hello clientrn");
connect(client, SIGNAL(readyRead()),
this, SLOT(startRead()));
}
void Server::startRead()
{
client->waitForReadyRead(3000);
QString buf=client->readAll();
qDebug() << buf;
static const QPoint minuteHand[3] = {
QPoint(7, 8),
QPoint(-7, 8),
QPoint(0, -40)
};
int side = qMin(200, 200);
QColor minuteColor(60, 60, 0);
QPixmap pixmap( 200, 200 );
pixmap.fill( Qt::red );
QPainter painter( &pixmap );
painter.setRenderHint(QPainter::Antialiasing);
painter.translate(200 / 2, 200 / 2);
painter.scale(side / 200.0, side / 200.0);
painter.setPen(Qt::NoPen);
for (int i = 0; i < 12; ++i) {
painter.drawLine(88, 0, 96, 0);
painter.rotate(30.0);
}
painter.setPen(Qt::NoPen);
painter.setBrush(minuteColor);
painter.save();
painter.rotate(240);
painter.drawConvexPolygon(minuteHand, 3);
painter.restore();
painter.setPen(minuteColor);
for (int j = 0; j < 60; ++j) {
if ((j % 5) != 0)
painter.drawLine(92, 0, 96, 0);
painter.rotate(6.0);
}
QLabel l;
l.setPixmap(pixmap);
l.show();
}
QString Server::getinfo()
{
qDebug()<< buf;
return buf;
}
main.cpp
#include "server.h"
#include <QApplication>
#include "analogclock.h"
#include "qlabel.h"
#include <QtGui>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Server s;
return a.exec();
}
应用程序输出
Starting C:QtQt5.3.0_1ToolsQtCreatorbinbuild-NHAJA-Desktop_Qt_5_3_0_MinGW_32bit-DebugdebugNHAJA.exe...
connected
accept connection
"11"
C:QtQt5.3.0_1ToolsQtCreatorbinbuild-NHAJA-Desktop_Qt_5_3_0_MinGW_32bit-DebugdebugNHAJA.exe exited with code 0
我真的很感激。
函数中创建的变量只有在调用函数时才存在,因此当函数完成执行时,变量会被消除,在您的情况下,QLabel也会被消除。
一个可能的解决方案是创建QLabel
作为类的成员:
服务器.h
private:
QLabel *label;
服务器.cpp
Server::Server(QObject *parent) : QObject(parent)
{
[...]
qDebug() << "connected";
label = new QLabel;
}
void Server::startRead()
{
[...]
for (int j = 0; j < 60; ++j) {
if ((j % 5) != 0)
painter.drawLine(92, 0, 96, 0);
painter.rotate(6.0);
}
label->setPixmap(pixmap);
label->show();
}