关于QT 5.6.1 (C++) 一些小细节

  1. QT5 简单本地局域网TCP通信

注意:*.pro文件中要增加 QT += network

TCP client端
	头文件中:
		#include 
		QTcpSocket *client;
		char *data="hello qt!";
	类的实现文件下,类的构造函数中:
		client = new QTcpSocket(this);
		client->connectToHost(QHostAddress("10.21.11.66"), 6665);
		client->write(data);
 
TCP server端
	头文件:
		#include 
		QTcpServer *server;
		QTcpSocket *clientConnection;
		public slots:
		    void readClient();
		    void acceptConnection();
	
	类的实现文件下,类的构造函数中:
		server = new QTcpServer();
		server->listen(QHostAddress::Any, 6665);
		connect(server, SIGNAL(newConnection()), this, SLOT(acceptConnection()));
		
	类的实现文件下:
		void 类名::acceptConnection()
		{
		    clientConnection = server->nextPendingConnection();
		    connect(clientConnection, SIGNAL(readyRead()), this, SLOT(readClient()));
		}
		void 类名::readClient()
		{
		    //QString str = clientConnection->readAll();
		    //或者
		    char buf[1024];
		    clientConnection->read(buf,1024);
		    qDebug("%s",buf);
		}

2.将QString的n类型转为字符串

           n=QString("yes");
           qDebug("%s",qPrintable(n));

3.设置大小的函数

    setMinimumSize
    setMaximumSize
    setFixedSize
    resize

4.#include //向QListWidget控件中写入内容

   QListWidget *liview=new QListWidget();

   QString ipa,ipn,ipg;

    ipa=ipn=ipg="hello qt.";

   liview->addItem(QString("ipaddress: %1 \n\n\nnetmask: %2 \n\n\ngateway: %3 ").arg(ipa,ipn,ipg));

5.QT creator c++ 中qt设计师界面(效果预览)

      ALT + shift + R 预览

6.UDP通信
UDP没有特定的server端和client端,简单来说就是向特定的ip发送报文,因此我把它分为发送端和接收端。
注意:在.pro文件中要添加QT += network,否则无法使用Qt的网络功能。

发送端
#include 
*.h文件:
	QUdpSocket *sender;
	sender = new QUdpSocket(this);
	QByteArray datagram = “hello world!”;

*.cpp文件:
	//UDP广播
	sender->writeDatagram(datagram.data(),datagram.size(),QHostAddress::Broadcast,6665);

	//向特定IP发送
	QHostAddress serverAddress = QHostAddress("10.21.11.66");
	sender->writeDatagram(datagram.data(), datagram.size(),serverAddress, 6665);

	/* writeDatagram函数原型,发送成功返回字节数,否则-1qint64 writeDatagram(const char *data,qint64 size,const QHostAddress &address,quint16 port)qint64 writeDatagram(const QByteArray &datagram,const QHostAddress &host,quint16 port)
	*/
——————————————————————————————————————————————————
UDP接收端
*.h文件:
	#include 
	QUdpSocket *receiver;
	//信号槽
	private slots:  
	    void readPendingDatagrams(); 
	
*.cpp文件:
	receiver = new QUdpSocket(this);
	receiver->bind(QHostAddress::LocalHost, 6665);
	connect(receiver, SIGNAL(readyRead()),this, SLOT(readPendingDatagrams()));
	void readPendingDatagrams()
	 {
	     while (receiver->hasPendingDatagrams()) {
	         QByteArray datagram;
	         datagram.resize(receiver->pendingDatagramSize());
	         receiver->readDatagram(datagram.data(), datagram.size());
	         //数据接收在datagram里/* readDatagram 函数原型
	qint64 readDatagram(char *data,qint64 maxSize,QHostAddress *address=0,quint16 *port=0)
	*/
	     }
	 }


你可能感兴趣的:(编程,QT,c++)