以下内容参考或转载自:
http://blog.csdn.net/sauphy/article/details/46136333
- 1、用QTime统计某函数执行消耗时间。
- QTime t;
- t.start();
- some_lengthy_task();
- qDebug("Time elapsed: %d ms", t.elapsed());
- 2、采用QLocalServer实现QT程序的单实例运行
- QLocalServer *server;
- server = new QLocalServer(this);
- if (!server->listen("fortune")) {
- QMessageBox::critical(this, tr("Fortune Server"),
- tr("Unable to start the server: %1.")
- .arg(server->errorString()));
- close();
- return;
- }
- 3、使用QStringList存储若干预定字符串。
- QStringList fortunes;
- fortunes << tr("You've been leading a dog's life. Stay off the furniture.")
- << tr("You've got to think about tomorrow.")
- << tr("You will be surprised by a loud noise.")
- << tr("You will feel hungry again in another hour.")
- << tr("You might have mail.")
- << tr("You cannot kill time without injuring eternity.")
- << tr("Computers are not intelligent. They only think they are.");
- fortunes.at(i); //访问第i个字符串
- 4、Qt中获取随机数
- qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));//播种子
- qrand() % size;//获取随机数
- 5、借助于QDataStream构建信令包(格式:dataSize_data)
- //发送端
- QByteArray block;
- QDataStream out(&block, QIODevice::WriteOnly);
- out.setVersion(QDataStream::Qt_4_0);
- out << (quint16)0;
- out << fortunes.at(qrand() % fortunes.size());
- out.device()->seek(0);
- out << (quint16)(block.size() - sizeof(quint16));
- //接收端
- QDataStream in(socket);
- in.setVersion(QDataStream::Qt_4_0);
- if (blockSize == 0) {
- if (socket->bytesAvailable() < (int)sizeof(quint16))
- return;
- in >> blockSize;
- }
- if (in.atEnd())
- return;
- QString nextFortune;
- in >> nextFortune;
- 6、QLocalServer的简单通信使用
- listen(name);
- //listen()客户的连接,一旦有外程序运行成功,则触发该信号
- connect(server, SIGNAL(newConnection()), this, SLOT(sendFortune()));
- //在槽函数中获取客户端Socket
- QLocalSocket *clientConnection = server->nextPendingConnection();
- connect(clientConnection, SIGNAL(disconnected()),
- clientConnection, SLOT(deleteLater()));
- clientConnection->write(block);
- clientConnection->flush();
- clientConnection->disconnectFromServer();
- 7、QLocalSocket的简单使用
- QLocalSocket * socket = new QLocalSocket(this);
- connect(socket, SIGNAL(readyRead()), this, SLOT(readFortune()));//监听可读数据
- connect(socket, SIGNAL(error(QLocalSocket::LocalSocketError)),//监听错误
- this, SLOT(displayError(QLocalSocket::LocalSocketError)));
- //向指定服务器连接
- socket->abort();//先断开已有连接
- socket->connectToServer(hostLineEdit->text());//Server和Client的name一致即可
- 8、定时器QTimer单次触发槽函数
- QTimer::singleShot(0, this, SLOT(requestNewFortune()));