以下是一个使用QT实现用户联网登录功能的简单示例:
#include <QtWidgets/QApplication>
#include <QtWidgets/QWidget>
#include <QtWidgets/QLabel>
#include <QtWidgets/QLineEdit>
#include <QtWidgets/QPushButton>
#include <QtNetwork/QTcpSocket>
class LoginWidget : public QWidget {
Q_OBJECT
public:
LoginWidget(QWidget *parent = nullptr) : QWidget(parent) {
QLabel *usernameLabel = new QLabel("Username:", this);
usernameLineEdit = new QLineEdit(this);
QLabel *passwordLabel = new QLabel("Password:", this);
passwordLineEdit = new QLineEdit(this);
passwordLineEdit->setEchoMode(QLineEdit::Password);
QPushButton *loginButton = new QPushButton("Login", this);
connect(loginButton, &QPushButton::clicked, this, &LoginWidget::attemptLogin);
QVBoxLayout *layout = new QVBoxLayout(this);
layout->addWidget(usernameLabel);
layout->addWidget(usernameLineEdit);
layout->addWidget(passwordLabel);
layout->addWidget(passwordLineEdit);
layout->addWidget(loginButton);
tcpSocket = new QTcpSocket(this);
}
private slots:
void attemptLogin() {
QString username = usernameLineEdit->text();
QString password = passwordLineEdit->text();
// 连接服务器,并发送登录请求
tcpSocket->connectToHost("服务器地址", 8080); // 替换为实际的服务器地址和端口号
if (tcpSocket->waitForConnected()) {
QString loginMessage = "LOGIN:" + username + ":" + password;
tcpSocket->write(loginMessage.toUtf8());
tcpSocket->waitForBytesWritten();
// 接收服务器响应
tcpSocket->waitForReadyRead();
QByteArray responseBytes = tcpSocket->readAll();
QString response = QString::fromUtf8(responseBytes);
// 处理服务器响应
if (response == "SUCCESS") {
QMessageBox::information(this, "Login", "Login successful");
} else {
QMessageBox::warning(this, "Login", "Login failed");
}
tcpSocket->disconnectFromHost();
} else {
QMessageBox::critical(this, "Error", "Could not connect to server");
}
}
private:
QLineEdit *usernameLineEdit;
QLineEdit *passwordLineEdit;
QTcpSocket *tcpSocket;
};
int main(int argc, char *argv[]) {
QApplication a(argc, argv);
LoginWidget w;
w.show();
return a.exec();
}
#include "main.moc"
请注意,在示例代码中的 connectToHost 函数中,需要替换为实际的服务器地址和端口号。此外,还需要根据具体需求进行错误处理、数据验证等操作。
内容由零声教学AI助手提供,问题来源于学员提问




