2023-12-05 Qt學習總結7


點擊 <C 語言編程核心突破> 快速C語言入門


Qt學習總結

  • 前言
  • 二十 QTcpSocket QTcpServer網絡庫
      • 服務端代碼:
      • 客戶端代碼
  • 二十一 QProcess進程類
  • 二十二 QThread線程
  • 總結


前言

要解決問題: 學習qt最核心知識, 多一個都不學.


二十 QTcpSocket QTcpServer網絡庫

QTcpSocketQTcpServer網絡庫是QT框架提供的網絡編程庫之一,用于實現TCP協議的網絡通信。

下面是QTcpSocketQTcpServer網絡庫中常用的C++函數:

QTcpSocket常用函數:

  1. QTcpSocket(QObject *parent = nullptr):構造函數。
  2. void connectToHost(const QString &hostName, quint16 port):連接到指定的主機名和端口。
  3. void disconnectFromHost():斷開與主機的連接。
  4. qint64 write(const char *data, qint64 maxSize):將數據寫入套接字。
  5. QByteArray read(qint64 maxSize):從套接字中讀取數據。
  6. bool waitForReadyRead(int msecs):等待套接字有可讀數據的信號。
  7. bool waitForConnected(int msecs):等待套接字成功連接到主機的信號。
  8. void flush():將寫入緩沖區的數據刷新到套接字。

QTcpServer常用函數:

  1. QTcpServer(QObject *parent = nullptr):構造函數。
  2. bool listen(const QHostAddress &address = QHostAddress::Any, quint16 port = 0):開始監聽指定的地址和端口。
  3. void close():關閉套接字,停止監聽。
  4. bool isListening() const:判斷是否正在監聽。
  5. QTcpSocket *nextPendingConnection():獲取下一個掛起的連接。
  6. qintptr socketDescriptor() const:獲取套接字的描述符。

以上是常用的QTcpSocketQTcpServer網絡庫C++函數,其他函數可參考QT官方文檔。

示例:

在這里插入圖片描述
在這里插入圖片描述
關閉客戶端, 再開啟客戶端連接, 發送信息
在這里插入圖片描述

在這里插入圖片描述

服務端代碼:

Widget.h

#ifndef WIDGET_H
#define WIDGET_H#include <QTcpServer>
#include <QTcpSocket>
#include <QWidget>QT_BEGIN_NAMESPACE
namespace Ui
{
class Widget;
}
QT_END_NAMESPACEclass Widget : public QWidget
{Q_OBJECTpublic:Widget(QWidget *parent = nullptr);~Widget();private slots:void on_cancelButton_clicked();void on_sendButton_clicked();public slots:void connectHandler();void reciveText();private:Ui::Widget *ui;QTcpServer *qtServer;QTcpSocket *qtSocket;
};
#endif // WIDGET_H

main.cpp

#include "Widget.h"#include <QApplication>
#include <QLocale>
#include <QTranslator>int main(int argc, char *argv[])
{QApplication a(argc, argv);QTranslator translator;const QStringList uiLanguages = QLocale::system().uiLanguages();for (const QString &locale : uiLanguages) {const QString baseName = "Learn_18_" + QLocale(locale).name();if (translator.load(":/i18n/" + baseName)) {a.installTranslator(&translator);break;}}Widget w;w.show();return a.exec();
}

Widget.cpp

#include "Widget.h"
#include "./ui_Widget.h"Widget::Widget(QWidget *parent): QWidget(parent), ui(new Ui::Widget), qtServer(new QTcpServer), qtSocket(nullptr)
{ui->setupUi(this);qtServer->listen(QHostAddress::AnyIPv4, 8000);connect(qtServer, SIGNAL(newConnection()), this, SLOT(connectHandler()));
}Widget::~Widget()
{delete ui;qtServer->close();if (qtSocket != nullptr){qtSocket->close();}
}void Widget::on_cancelButton_clicked()
{this->close();
}void Widget::connectHandler()
{if (qtSocket != nullptr){qtSocket->disconnect();qtSocket->disconnectFromHost();qtSocket->close();}qtSocket = qtServer->nextPendingConnection();ui->ipLineEdit->setText(qtSocket->peerAddress().toString());ui->portLineEdit->setText(QString::number(qtSocket->peerPort()));connect(qtSocket, SIGNAL(readyRead()), this, SLOT(reciveText()));connect(qtSocket, &QTcpSocket::disconnected,[this]() { qDebug() << "Disconnected"; });
}void Widget::reciveText()
{ui->reciveLineEdit->setText(QString(qtSocket->readAll()));
}void Widget::on_sendButton_clicked()
{if (qtSocket->isValid()){qtSocket->write(ui->sendLineEdit->text().toUtf8());}else{qDebug() << "unconnect";}
}

ui_Widget.h

/********************************************************************************
** Form generated from reading UI file 'Widget.ui'
**
** Created by: Qt User Interface Compiler version 6.5.2
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/#ifndef UI_WIDGET_H
#define UI_WIDGET_H#include <QtCore/QVariant>
#include <QtWidgets/QApplication>
#include <QtWidgets/QFormLayout>
#include <QtWidgets/QHBoxLayout>
#include <QtWidgets/QLabel>
#include <QtWidgets/QLineEdit>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QWidget>QT_BEGIN_NAMESPACEclass Ui_Widget
{
public:QLabel *label_5;QWidget *widget;QFormLayout *formLayout;QLabel *label;QLineEdit *ipLineEdit;QLabel *label_2;QLineEdit *portLineEdit;QLabel *label_3;QLineEdit *reciveLineEdit;QLabel *label_4;QLineEdit *sendLineEdit;QWidget *widget1;QHBoxLayout *horizontalLayout;QPushButton *sendButton;QPushButton *cancelButton;void setupUi(QWidget *Widget){if (Widget->objectName().isEmpty())Widget->setObjectName("Widget");Widget->resize(482, 419);label_5 = new QLabel(Widget);label_5->setObjectName("label_5");label_5->setGeometry(QRect(190, 20, 92, 50));label_5->setStyleSheet(QString::fromUtf8("font: 700 24pt \"\351\230\277\351\207\214\345\267\264\345\267\264\346\231\256\346\203\240\344\275\223 B\";"));widget = new QWidget(Widget);widget->setObjectName("widget");widget->setGeometry(QRect(10, 90, 461, 220));formLayout = new QFormLayout(widget);formLayout->setObjectName("formLayout");formLayout->setContentsMargins(0, 0, 0, 0);label = new QLabel(widget);label->setObjectName("label");label->setStyleSheet(QString::fromUtf8("font: 700 24pt \"\351\230\277\351\207\214\345\267\264\345\267\264\346\231\256\346\203\240\344\275\223 B\";"));formLayout->setWidget(0, QFormLayout::LabelRole, label);ipLineEdit = new QLineEdit(widget);ipLineEdit->setObjectName("ipLineEdit");ipLineEdit->setStyleSheet(QString::fromUtf8("font: 700 24pt \"\351\230\277\351\207\214\345\267\264\345\267\264\346\231\256\346\203\240\344\275\223 B\";"));formLayout->setWidget(0, QFormLayout::FieldRole, ipLineEdit);label_2 = new QLabel(widget);label_2->setObjectName("label_2");label_2->setStyleSheet(QString::fromUtf8("font: 700 24pt \"\351\230\277\351\207\214\345\267\264\345\267\264\346\231\256\346\203\240\344\275\223 B\";"));formLayout->setWidget(1, QFormLayout::LabelRole, label_2);portLineEdit = new QLineEdit(widget);portLineEdit->setObjectName("portLineEdit");portLineEdit->setStyleSheet(QString::fromUtf8("font: 700 24pt \"\351\230\277\351\207\214\345\267\264\345\267\264\346\231\256\346\203\240\344\275\223 B\";"));formLayout->setWidget(1, QFormLayout::FieldRole, portLineEdit);label_3 = new QLabel(widget);label_3->setObjectName("label_3");label_3->setStyleSheet(QString::fromUtf8("font: 700 24pt \"\351\230\277\351\207\214\345\267\264\345\267\264\346\231\256\346\203\240\344\275\223 B\";"));formLayout->setWidget(2, QFormLayout::LabelRole, label_3);reciveLineEdit = new QLineEdit(widget);reciveLineEdit->setObjectName("reciveLineEdit");reciveLineEdit->setStyleSheet(QString::fromUtf8("font: 700 24pt \"\351\230\277\351\207\214\345\267\264\345\267\264\346\231\256\346\203\240\344\275\223 B\";"));formLayout->setWidget(2, QFormLayout::FieldRole, reciveLineEdit);label_4 = new QLabel(widget);label_4->setObjectName("label_4");label_4->setStyleSheet(QString::fromUtf8("font: 700 24pt \"\351\230\277\351\207\214\345\267\264\345\267\264\346\231\256\346\203\240\344\275\223 B\";"));formLayout->setWidget(3, QFormLayout::LabelRole, label_4);sendLineEdit = new QLineEdit(widget);sendLineEdit->setObjectName("sendLineEdit");sendLineEdit->setStyleSheet(QString::fromUtf8("font: 700 24pt \"\351\230\277\351\207\214\345\267\264\345\267\264\346\231\256\346\203\240\344\275\223 B\";"));formLayout->setWidget(3, QFormLayout::FieldRole, sendLineEdit);widget1 = new QWidget(Widget);widget1->setObjectName("widget1");widget1->setGeometry(QRect(10, 330, 461, 54));horizontalLayout = new QHBoxLayout(widget1);horizontalLayout->setObjectName("horizontalLayout");horizontalLayout->setContentsMargins(0, 0, 0, 0);sendButton = new QPushButton(widget1);sendButton->setObjectName("sendButton");sendButton->setStyleSheet(QString::fromUtf8("font: 700 24pt \"\351\230\277\351\207\214\345\267\264\345\267\264\346\231\256\346\203\240\344\275\223 B\";"));horizontalLayout->addWidget(sendButton);cancelButton = new QPushButton(widget1);cancelButton->setObjectName("cancelButton");cancelButton->setStyleSheet(QString::fromUtf8("font: 700 24pt \"\351\230\277\351\207\214\345\267\264\345\267\264\346\231\256\346\203\240\344\275\223 B\";"));horizontalLayout->addWidget(cancelButton);retranslateUi(Widget);QMetaObject::connectSlotsByName(Widget);} // setupUivoid retranslateUi(QWidget *Widget){Widget->setWindowTitle(QCoreApplication::translate("Widget", "Widget", nullptr));label_5->setText(QCoreApplication::translate("Widget", "\346\234\215\345\212\241\347\253\257", nullptr));label->setText(QCoreApplication::translate("Widget", "IP\345\234\260\345\235\200", nullptr));label_2->setText(QCoreApplication::translate("Widget", "\347\253\257\345\217\243\345\217\267", nullptr));label_3->setText(QCoreApplication::translate("Widget", "\346\224\266  \346\226\207", nullptr));label_4->setText(QCoreApplication::translate("Widget", "\345\217\221  \346\226\207", nullptr));sendButton->setText(QCoreApplication::translate("Widget", "\345\217\221\351\200\201", nullptr));cancelButton->setText(QCoreApplication::translate("Widget", "\345\217\226\346\266\210", nullptr));} // retranslateUi};namespace Ui {class Widget: public Ui_Widget {};
} // namespace UiQT_END_NAMESPACE#endif // UI_WIDGET_H

客戶端代碼

Widget.h

#ifndef WIDGET_H
#define WIDGET_H#include <QTcpSocket>
#include <QWidget>QT_BEGIN_NAMESPACE
namespace Ui
{
class Widget;
}
QT_END_NAMESPACEclass Widget : public QWidget
{Q_OBJECTpublic:Widget(QWidget *parent = nullptr);~Widget();private slots:void on_linkButton_clicked();void on_sendButton_clicked();void on_cancelButton_clicked();public slots:void recieveText();private:Ui::Widget *ui;QTcpSocket *socket;
};
#endif // WIDGET_H

main.cpp

#include "Widget.h"#include <QApplication>
#include <QLocale>
#include <QTranslator>int main(int argc, char *argv[])
{QApplication a(argc, argv);QTranslator translator;const QStringList uiLanguages = QLocale::system().uiLanguages();for (const QString &locale : uiLanguages) {const QString baseName = "Learn_19_" + QLocale(locale).name();if (translator.load(":/i18n/" + baseName)) {a.installTranslator(&translator);break;}}Widget w;w.show();return a.exec();
}

Widget.cpp

#include "Widget.h"
#include "./ui_Widget.h"Widget::Widget(QWidget *parent): QWidget(parent), ui(new Ui::Widget), socket(new QTcpSocket)
{ui->setupUi(this);connect(socket, &QTcpSocket::connected, [this]() { qDebug() << "OK"; });connect(socket, SIGNAL(readyRead()), this, SLOT(recieveText()));connect(socket, &QTcpSocket::disconnected,[this]() { qDebug() << "Disconnected"; });
}Widget::~Widget()
{delete ui;
}void Widget::on_linkButton_clicked()
{// socket->disconnect();QString ipAdd(ui->ipLineEdit->text());socket->connectToHost(QHostAddress(ipAdd),ui->portLineEdit->text().toUShort());
}void Widget::on_sendButton_clicked()
{if (socket->isValid()){socket->write(ui->sendLineEdit->text().toUtf8());}
}void Widget::on_cancelButton_clicked()
{this->close();
}void Widget::recieveText()
{QString res = QString::fromUtf8(socket->readAll());ui->recieveLineEdit->setText(res);qDebug() << res;
}

ui_Widget.h

/********************************************************************************
** Form generated from reading UI file 'Widget.ui'
**
** Created by: Qt User Interface Compiler version 6.5.2
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/#ifndef UI_WIDGET_H
#define UI_WIDGET_H#include <QtCore/QVariant>
#include <QtWidgets/QApplication>
#include <QtWidgets/QFormLayout>
#include <QtWidgets/QHBoxLayout>
#include <QtWidgets/QLabel>
#include <QtWidgets/QLineEdit>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QWidget>QT_BEGIN_NAMESPACEclass Ui_Widget
{
public:QLabel *label_5;QWidget *layoutWidget;QFormLayout *formLayout;QLabel *label;QLineEdit *ipLineEdit;QLabel *label_2;QLineEdit *portLineEdit;QLabel *label_3;QLineEdit *sendLineEdit;QLabel *label_4;QLineEdit *recieveLineEdit;QWidget *layoutWidget1;QHBoxLayout *horizontalLayout;QPushButton *linkButton;QPushButton *sendButton;QPushButton *cancelButton;void setupUi(QWidget *Widget){if (Widget->objectName().isEmpty())Widget->setObjectName("Widget");Widget->resize(555, 400);label_5 = new QLabel(Widget);label_5->setObjectName("label_5");label_5->setGeometry(QRect(220, 10, 101, 50));label_5->setStyleSheet(QString::fromUtf8("font: 700 24pt \"\351\230\277\351\207\214\345\267\264\345\267\264\346\231\256\346\203\240\344\275\223 B\";"));layoutWidget = new QWidget(Widget);layoutWidget->setObjectName("layoutWidget");layoutWidget->setGeometry(QRect(10, 80, 541, 220));formLayout = new QFormLayout(layoutWidget);formLayout->setObjectName("formLayout");formLayout->setContentsMargins(0, 0, 0, 0);label = new QLabel(layoutWidget);label->setObjectName("label");label->setStyleSheet(QString::fromUtf8("font: 700 24pt \"\351\230\277\351\207\214\345\267\264\345\267\264\346\231\256\346\203\240\344\275\223 B\";"));formLayout->setWidget(0, QFormLayout::LabelRole, label);ipLineEdit = new QLineEdit(layoutWidget);ipLineEdit->setObjectName("ipLineEdit");ipLineEdit->setStyleSheet(QString::fromUtf8("font: 700 24pt \"\351\230\277\351\207\214\345\267\264\345\267\264\346\231\256\346\203\240\344\275\223 B\";"));formLayout->setWidget(0, QFormLayout::FieldRole, ipLineEdit);label_2 = new QLabel(layoutWidget);label_2->setObjectName("label_2");label_2->setStyleSheet(QString::fromUtf8("font: 700 24pt \"\351\230\277\351\207\214\345\267\264\345\267\264\346\231\256\346\203\240\344\275\223 B\";"));formLayout->setWidget(1, QFormLayout::LabelRole, label_2);portLineEdit = new QLineEdit(layoutWidget);portLineEdit->setObjectName("portLineEdit");portLineEdit->setStyleSheet(QString::fromUtf8("font: 700 24pt \"\351\230\277\351\207\214\345\267\264\345\267\264\346\231\256\346\203\240\344\275\223 B\";"));formLayout->setWidget(1, QFormLayout::FieldRole, portLineEdit);label_3 = new QLabel(layoutWidget);label_3->setObjectName("label_3");label_3->setStyleSheet(QString::fromUtf8("font: 700 24pt \"\351\230\277\351\207\214\345\267\264\345\267\264\346\231\256\346\203\240\344\275\223 B\";"));formLayout->setWidget(2, QFormLayout::LabelRole, label_3);sendLineEdit = new QLineEdit(layoutWidget);sendLineEdit->setObjectName("sendLineEdit");sendLineEdit->setStyleSheet(QString::fromUtf8("font: 700 24pt \"\351\230\277\351\207\214\345\267\264\345\267\264\346\231\256\346\203\240\344\275\223 B\";"));formLayout->setWidget(2, QFormLayout::FieldRole, sendLineEdit);label_4 = new QLabel(layoutWidget);label_4->setObjectName("label_4");label_4->setStyleSheet(QString::fromUtf8("font: 700 24pt \"\351\230\277\351\207\214\345\267\264\345\267\264\346\231\256\346\203\240\344\275\223 B\";"));formLayout->setWidget(3, QFormLayout::LabelRole, label_4);recieveLineEdit = new QLineEdit(layoutWidget);recieveLineEdit->setObjectName("recieveLineEdit");recieveLineEdit->setStyleSheet(QString::fromUtf8("font: 700 24pt \"\351\230\277\351\207\214\345\267\264\345\267\264\346\231\256\346\203\240\344\275\223 B\";"));formLayout->setWidget(3, QFormLayout::FieldRole, recieveLineEdit);layoutWidget1 = new QWidget(Widget);layoutWidget1->setObjectName("layoutWidget1");layoutWidget1->setGeometry(QRect(10, 330, 531, 54));horizontalLayout = new QHBoxLayout(layoutWidget1);horizontalLayout->setObjectName("horizontalLayout");horizontalLayout->setContentsMargins(0, 0, 0, 0);linkButton = new QPushButton(layoutWidget1);linkButton->setObjectName("linkButton");linkButton->setStyleSheet(QString::fromUtf8("font: 700 24pt \"\351\230\277\351\207\214\345\267\264\345\267\264\346\231\256\346\203\240\344\275\223 B\";"));horizontalLayout->addWidget(linkButton);sendButton = new QPushButton(layoutWidget1);sendButton->setObjectName("sendButton");sendButton->setStyleSheet(QString::fromUtf8("font: 700 24pt \"\351\230\277\351\207\214\345\267\264\345\267\264\346\231\256\346\203\240\344\275\223 B\";"));horizontalLayout->addWidget(sendButton);cancelButton = new QPushButton(layoutWidget1);cancelButton->setObjectName("cancelButton");cancelButton->setStyleSheet(QString::fromUtf8("font: 700 24pt \"\351\230\277\351\207\214\345\267\264\345\267\264\346\231\256\346\203\240\344\275\223 B\";"));horizontalLayout->addWidget(cancelButton);retranslateUi(Widget);QMetaObject::connectSlotsByName(Widget);} // setupUivoid retranslateUi(QWidget *Widget){Widget->setWindowTitle(QCoreApplication::translate("Widget", "Widget", nullptr));label_5->setText(QCoreApplication::translate("Widget", "\345\256\242\346\210\267\347\253\257", nullptr));label->setText(QCoreApplication::translate("Widget", "IP", nullptr));ipLineEdit->setText(QCoreApplication::translate("Widget", "127.0.0.1", nullptr));label_2->setText(QCoreApplication::translate("Widget", "\347\253\257\345\217\243", nullptr));portLineEdit->setText(QCoreApplication::translate("Widget", "8000", nullptr));label_3->setText(QCoreApplication::translate("Widget", "\345\217\221\351\200\201", nullptr));label_4->setText(QCoreApplication::translate("Widget", "\346\216\245\346\224\266", nullptr));linkButton->setText(QCoreApplication::translate("Widget", "\350\277\236\346\216\245", nullptr));sendButton->setText(QCoreApplication::translate("Widget", "\345\217\221\351\200\201", nullptr));cancelButton->setText(QCoreApplication::translate("Widget", "\345\217\226\346\266\210", nullptr));} // retranslateUi};namespace Ui {class Widget: public Ui_Widget {};
} // namespace UiQT_END_NAMESPACE#endif // UI_WIDGET_H

通常在建立qt項目時, 不會自動鏈接Network頭文件及庫文件, 需要在cmake文件中加入:

find_package(Qt${QT_VERSION_MAJOR} REQUIRED COMPONENTS Network)
target_link_libraries(Learn_18 PRIVATE Qt${QT_VERSION_MAJOR}::Network)

其中Learn_18是項目名, 根據你的項目更改.

二十一 QProcess進程類

QProcess是一個進程管理類,它允許您啟動外部程序和與它們通信。

QProcess支持同步和異步啟動,也可以使用管道和I / O重定向向子進程發送和接收數據。

下面是常用函數列表:

  1. QProcess(const QStringList &arguments = QStringList(), QObject *parent = nullptr) 該函數可以創建一個用于啟動外部程序的QProcess對象,可以設置啟動參數。

  2. setProgram(QString program) 設置要啟動的程序或可執行文件的路徑。

  3. setArguments(const QStringList &arguments) 設置啟動參數列表。

  4. setWorkingDirectory(QString dir) 設置運行外部程序的工作目錄。

  5. start(const QString &program, const QStringList &arguments = {}, OpenMode mode = ReadWrite); 啟動外部程序。

  6. waitForStarted(int msecs = 30000) 等待外部程序啟動,返回true表示啟動成功,false表示啟動失敗。

  7. waitForFinished(int msecs = 30000) 等待外部程序執行完成,返回true表示執行完成,false表示超時或執行失敗。

  8. readAllStandardOutput() 讀取外部程序的標準輸出,返回一個QByteArray

  9. readAllStandardError() 讀取外部程序的標準錯誤輸出,返回一個QByteArray

  10. void write(const QByteArray &byteArray) 向外部程序的標準輸入寫入數據。

您還可以使用QIODevice API通過管道與子進程通信。

常見的用法是通過標準輸入輸出管道或錯誤輸出管道發送和接收數據。

您還可以使用readAllStandardOutput()readAllStandardError()函數來獲取進程的輸出和錯誤輸出。

在非Windows平臺上,QProcess使用QAbstractEventDispatcher來監視子進程。

使用QProcess的事件循環時,如果有進程事件到達,將調用QProcess的虛擬函數來處理該事件。

如果使用waitForStarted()waitForFinished()之類的功能等待進程,則QProcess將在事件循環內等待進程事件的到來。

Windows上,QProcess使用WaitHandle實現進程監視,并且可以兼容在Windows上使用其他Qt的進程相關類。

示例:
用進程類實現一個應用, 當點擊run, 從命令和參數文本框獲取命令文本, 并啟動進程, 將結果返回到結果文本框中.
在這里插入圖片描述
Widget.h

#ifndef WIDGET_H
#define WIDGET_H#include <QProcess>
#include <QWidget>QT_BEGIN_NAMESPACE
namespace Ui
{
class Widget;
}
QT_END_NAMESPACEclass Widget : public QWidget
{Q_OBJECTpublic:Widget(QWidget *parent = nullptr);~Widget();private slots:void on_runButton_clicked();private:Ui::Widget *ui;
};
#endif // WIDGET_H

main.cpp

#include "Widget.h"#include <QApplication>
#include <QLocale>
#include <QTranslator>int main(int argc, char *argv[])
{QApplication a(argc, argv);QTranslator translator;const QStringList uiLanguages = QLocale::system().uiLanguages();for (const QString &locale : uiLanguages) {const QString baseName = "Learn_20_" + QLocale(locale).name();if (translator.load(":/i18n/" + baseName)) {a.installTranslator(&translator);break;}}Widget w;w.show();return a.exec();
}

Widget.cpp

#include "Widget.h"
#include "./ui_Widget.h"Widget::Widget(QWidget *parent): QWidget(parent), ui(new Ui::Widget)
{ui->setupUi(this);
}Widget::~Widget()
{delete ui;
}void Widget::on_runButton_clicked()
{QProcess process(this);QStringList qsl;qsl << ui->optionLineEdit->text();process.start(ui->commendLineEdit->text(), qsl);if (process.waitForStarted() && process.waitForFinished()){qDebug() << "OK";}QByteArray output = process.readAllStandardOutput();ui->resultTextEdit->setText(QString::fromLocal8Bit(output));qDebug() << QString::fromLocal8Bit(output);
}

ui_Widget.h

/********************************************************************************
** Form generated from reading UI file 'Widget.ui'
**
** Created by: Qt User Interface Compiler version 6.5.2
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/#ifndef UI_WIDGET_H
#define UI_WIDGET_H#include <QtCore/QVariant>
#include <QtWidgets/QApplication>
#include <QtWidgets/QFormLayout>
#include <QtWidgets/QLabel>
#include <QtWidgets/QLineEdit>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QTextEdit>
#include <QtWidgets/QWidget>QT_BEGIN_NAMESPACEclass Ui_Widget
{
public:QPushButton *runButton;QTextEdit *resultTextEdit;QWidget *layoutWidget;QFormLayout *formLayout;QLabel *label;QLabel *label_2;QLineEdit *commendLineEdit;QLineEdit *optionLineEdit;void setupUi(QWidget *Widget){if (Widget->objectName().isEmpty())Widget->setObjectName("Widget");Widget->resize(508, 577);runButton = new QPushButton(Widget);runButton->setObjectName("runButton");runButton->setGeometry(QRect(10, 530, 81, 31));runButton->setStyleSheet(QString::fromUtf8("font: 700 16pt \"\351\230\277\351\207\214\345\267\264\345\267\264\346\231\256\346\203\240\344\275\223 B\";"));resultTextEdit = new QTextEdit(Widget);resultTextEdit->setObjectName("resultTextEdit");resultTextEdit->setGeometry(QRect(10, 90, 491, 421));layoutWidget = new QWidget(Widget);layoutWidget->setObjectName("layoutWidget");layoutWidget->setGeometry(QRect(10, 10, 491, 72));formLayout = new QFormLayout(layoutWidget);formLayout->setObjectName("formLayout");formLayout->setContentsMargins(0, 0, 0, 0);label = new QLabel(layoutWidget);label->setObjectName("label");label->setStyleSheet(QString::fromUtf8("font: 700 16pt \"\351\230\277\351\207\214\345\267\264\345\267\264\346\231\256\346\203\240\344\275\223 B\";"));formLayout->setWidget(0, QFormLayout::LabelRole, label);label_2 = new QLabel(layoutWidget);label_2->setObjectName("label_2");label_2->setStyleSheet(QString::fromUtf8("font: 700 16pt \"\351\230\277\351\207\214\345\267\264\345\267\264\346\231\256\346\203\240\344\275\223 B\";"));formLayout->setWidget(0, QFormLayout::FieldRole, label_2);commendLineEdit = new QLineEdit(layoutWidget);commendLineEdit->setObjectName("commendLineEdit");commendLineEdit->setStyleSheet(QString::fromUtf8("font: 700 16pt \"\351\230\277\351\207\214\345\267\264\345\267\264\346\231\256\346\203\240\344\275\223 B\";"));formLayout->setWidget(1, QFormLayout::LabelRole, commendLineEdit);optionLineEdit = new QLineEdit(layoutWidget);optionLineEdit->setObjectName("optionLineEdit");optionLineEdit->setStyleSheet(QString::fromUtf8("font: 700 16pt \"\351\230\277\351\207\214\345\267\264\345\267\264\346\231\256\346\203\240\344\275\223 B\";"));formLayout->setWidget(1, QFormLayout::FieldRole, optionLineEdit);retranslateUi(Widget);QMetaObject::connectSlotsByName(Widget);} // setupUivoid retranslateUi(QWidget *Widget){Widget->setWindowTitle(QCoreApplication::translate("Widget", "Widget", nullptr));runButton->setText(QCoreApplication::translate("Widget", "run", nullptr));label->setText(QCoreApplication::translate("Widget", "\345\221\275\344\273\244", nullptr));label_2->setText(QCoreApplication::translate("Widget", "\345\217\202\346\225\260", nullptr));} // retranslateUi};namespace Ui {class Widget: public Ui_Widget {};
} // namespace UiQT_END_NAMESPACE#endif // UI_WIDGET_H

二十二 QThread線程

QThread是Qt框架中的線程類,它提供了一個跨平臺的線程類庫,可以在Qt應用程序中實現多線程編程,實現并發執行任務的能力。

QThread類通過繼承QThread并重載run()函數來實現自己的線程。

run()函數中包含了線程的邏輯代碼,線程啟動時會自動調用run()函數。

QThread還提供了一些常用的函數,如start()函數開始線程,quit()函數結束線程,wait()函數等待線程結束等。

常用函數:

start():啟動線程,該函數將會調用run()函數;

sleep():暫停當前線程,單位毫秒;

quit():結束線程,類似于Thread類的Stop方法;

wait():等待當前線程執行完畢,阻塞當前線程;

finished():當線程執行結束時會發出該信號;

terminate():強制關閉線程,類似于Thread類的Abort方法。

C++示例:用線程返回相加結果, 并在主線程輸出
在這里插入圖片描述
我們實現一個myThread線程類, 繼承自QThread, 當觸發計算時, 調用槽函數, 生成線程, 線程運算相加結果, 并通過信號槽機制返回給主線程, 進行顯示.

myThread.h

#ifndef MYTHREAD_H
#define MYTHREAD_H#include <QThread>class myThread : public QThread
{Q_OBJECTpublic:explicit myThread(QObject *parent = nullptr, int numA_ = 0, int numB_ = 0);void run() override;signals:void result(int);private:int numA;int numB;
};#endif // MYTHREAD_H

myThread.cpp

#include "myThread.h"myThread::myThread(QObject *parent, int numA_, int numB_): QThread{parent}, numA(numA_), numB(numB_)
{}void myThread::run()
{emit result(numA + numB);
}

通過簡單的封裝, 可以很容易的將數據傳給線程, 通過信號槽機制, 又很容易的可以將結果返回, 相比C或C++原生thread, 已經人性化的一塌糊度了.

當然, 效率問題不在本文探討之列.

Widget.h

#ifndef WIDGET_H
#define WIDGET_H#include <QWidget>QT_BEGIN_NAMESPACE
namespace Ui
{
class Widget;
}
QT_END_NAMESPACEclass Widget : public QWidget
{Q_OBJECTpublic:Widget(QWidget *parent = nullptr);~Widget();public slots:void getResult(int res);private slots:void on_pushButton_clicked();private:Ui::Widget *ui;
};
#endif // WIDGET_H

Widget.cpp

#include "Widget.h"
#include "./ui_Widget.h"
#include "myThread.h"Widget::Widget(QWidget *parent): QWidget(parent), ui(new Ui::Widget)
{ui->setupUi(this);
}Widget::~Widget()
{delete ui;
}void Widget::on_pushButton_clicked()
{int numA = ui->lineEditA->text().toInt();int numB = ui->lineEditB->text().toInt();myThread *qthrd = new myThread(this, numA, numB);qthrd->start();connect(qthrd, SIGNAL(result(int)), this, SLOT(getResult(int)));qthrd->wait();qthrd->deleteLater();
}void Widget::getResult(int res)
{ui->lineEditSum->setText(QString::number(res));
}

總結

二十 QTcpSocket QTcpServer網絡庫
服務端代碼:
客戶端代碼
二十一 QProcess進程類
二十二 QThread線程


點擊 <C 語言編程核心突破> 快速C語言入門


本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/212833.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/212833.shtml
英文地址,請注明出處:http://en.pswp.cn/news/212833.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

持續集成交付CICD:Jenkins流水線實現Nexus制品晉級策略

目錄 一、理論 1.開發測試運維環境 二、實驗 1.Nexus制品晉級策略 一、理論 1.開發測試運維環境 &#xff08;1&#xff09;環境 1&#xff09;持續集成開發環境&#xff08;DEV: Development Environment&#xff09; 直接通過源代碼編譯打包&#xff0c;其會跑單元測試…

python 筆記 :trajectory_distance包(如何可以正確使用)【debug篇】

包的地址&#xff1a;maikol-solis/trajectory_distance (github.com) 1 模塊介紹 用Cython實現的Python模塊&#xff0c;用于計算二維軌跡之間的距離 trajectory_distance包提供了9種軌跡間的距離計算方法&#xff1a; SSPD&#xff08;對稱線段路徑距離&#xff09;OWD&a…

機器學習算法(9)——集成技術(Bagging——隨機森林分類器和回歸)

一、說明 在這篇文章&#xff0c;我將向您解釋集成技術和著名的集成技術之一&#xff0c;它屬于裝袋技術&#xff0c;稱為隨機森林分類器和回歸。 集成技術是機器學習技術&#xff0c;它結合多個基本模塊和模型來創建最佳預測模型。為了更好地理解這個定義&#xff0c;我們需要…

WLAN配置實驗

本文記錄了WLAN配置實踐的過程&#xff0c;該操作在華為HCIA中屬于相對較復雜的實驗&#xff0c;記錄過程備忘。這里不就WLAN原理解釋&#xff0c;僅進行配置實踐&#xff0c;可以作為學習原理時候的參考。本文使用華為ENSP進行仿真。實驗拓撲圖如下&#xff1a; 1.WLAN工作流程…

【electron】外語函數接口 FFI

? 目錄 ? &#x1f6eb; 導讀需求開發環境 1?? FFI概念優點注意事項 2?? 【廢棄】node-ffi3?? node-ffi-napi安裝&#xff08;windows系統下&#xff09;示例&#xff1a;MessageBoxA、NtSuspendProcess 4?? node-win32-api安裝示例&#xff1a;查找窗口并設置窗口標…

UE5數據傳遞-紋理貼圖

期待結果&#xff1a; 流程 1. 通過C寫入數據到紋理貼圖 2. 在材質中通過采樣能正確讀取寫入的數值 踩坑&#xff1a; 1. UE5之后&#xff0c;需要設置采樣類型&#xff0c;才能達到上圖效果&#xff0c;默認采樣類型做了插值計算 FColor中寫入 PF_B8G8R8A8 UTexture2D* Conve…

第四題:憧憬(JavaPythonC++實現)【第六屆傳智杯-新增場次-程序設計挑戰賽解題分析詳解復盤】

本文僅為【2023傳智杯-第二場】第六屆傳智杯程序設計挑戰賽-題目解題分析詳解的解題個人筆記,個人解題分析記錄。 本文包含:第六屆傳智杯程序設計挑戰賽題目、解題思路分析、解題代碼、解題代碼詳解(Java&Python&C++實現) 文章目錄 更新進度記錄第四題:憧憬(Java…

AI 繪畫 | Stable Diffusion 藝術二維碼制作

前言 這篇文章教會你如果用Stable Diffusion WEB UI制作藝術二維碼,什么是藝術二維碼呢?就是普通二維碼和藝術圖片融合后的二維碼圖片,如下圖所示。主要原理還是使用controlNet的control_v1p_sd15_qrcode_monster模型和光影模型control_v1p_sd15_brightness。 教程 準備…

【論文閱讀筆記】NeRF+Mip-NeRF+Instant-NGP

目錄 前言NeRF神經輻射場體渲染連續體渲染體渲染離散化 方法位置編碼分層采樣體渲染推導公式&#xff08;1&#xff09;到公式&#xff08;2&#xff09;部分代碼解讀相機變換&#xff08;重要&#xff01;&#xff09; Mip-NerfTo do Instant-NGPTo do 前言 NeRF是NeRF系列的…

DIP——邊緣提取與分割

1.使用canny算法進行邊緣提取 本實驗比較簡單&#xff0c;基本思路是對原圖像進行一個高斯模糊處理&#xff0c;用于去噪&#xff0c;之后轉換為灰度圖&#xff0c;直接調用cv庫中的canny記性邊緣提取。若想直接得到彩色邊緣&#xff0c;則通過按位與操作&#xff0c;將原始彩色…

SQLMap進階使用

預計更新SQL注入概述 1.1 SQL注入攻擊概述 1.2 SQL注入漏洞分類 1.3 SQL注入攻擊的危害 SQLMap介紹 2.1 SQLMap簡介 2.2 SQLMap安裝與配置 2.3 SQLMap基本用法 SQLMap進階使用 3.1 SQLMap高級用法 3.2 SQLMap配置文件詳解 3.3 SQLMap插件的使用 SQL注入漏洞檢測 4.1 SQL注入…

ingress介紹和ingress通過LoadBalancer暴露服務配置

目錄 一.ingress基本原理介紹 1.將原有用于暴露服務和負載均衡的服務的三四層負載均衡變為一個七層負載均衡 2.controller和ingress 3.通過下面這個圖可能會有更直觀的理解 二.為什么會出現ingress 1.NodePort存在缺點 2.LoadBalancer存在缺點 三.ingress三種暴露服務的…

7-6 通訊錄排序

輸入n個朋友的信息&#xff0c;包括姓名、生日、電話號碼&#xff0c;本題要求編寫程序&#xff0c;按照年齡從大到小的順序依次輸出通訊錄。題目保證所有人的生日均不相同。 輸入格式: 輸入第一行給出正整數n&#xff08;<10&#xff09;。隨后n行&#xff0c;每行按照“…

基于JavaWeb+SSM+Vue微信小程序的科創微應用平臺系統的設計和實現

基于JavaWebSSMVue微信小程序的科創微應用平臺系統的設計和實現 源碼獲取入口Lun文目錄前言主要技術系統設計功能截圖訂閱經典源碼專欄Java項目精品實戰案例《500套》 源碼獲取 源碼獲取入口 Lun文目錄 1系統概述 1 1.1 研究背景 1 1.2研究目的 1 1.3系統設計思想 1 2相關技術…

Linux Component概述和高通component的使用

1 Linux為什么要引入Component框架&#xff1f; 為了讓subsystem按照一定順序初始化設備才提出來的。 subsystem中由很多設備模塊&#xff0c;內核加載這些模塊的時間不確定。子系統內有些模塊是需要依賴其它模塊先初始化才能進行自己初始化工作(例如v4l2 subdev和v4l2 video …

kubebuilder開發operator

安裝kubebuilder前 需要有kubernetes環境和golang環境 官網&#xff1a;https://go.kubebuilder.io/ 安裝kubebuilder #下載 wget https://go.kubebuilder.io/dl/latest/$(go env GOOS)/$(go env GOARCH) #改名kubebuilder后加權限 chmod x kubebuilder #放到環境變量里 mv k…

【C語言程序設計】編寫簡單的C程序

目錄 前言 一、程序設計 二、程序改錯 三、程序完善 總結 &#x1f308;嗨&#xff01;我是Filotimo__&#x1f308;。很高興與大家相識&#xff0c;希望我的博客能對你有所幫助。 &#x1f4a1;本文由Filotimo__??原創&#xff0c;首發于CSDN&#x1f4da;。 &#x1f4e3;如…

unity 2d 入門 飛翔小鳥 死亡 顯示GameOver(十四)

1、添加Img create->ui->img 把圖片拖進去 2、和分數一樣、調整位置 3、修改角色腳本 using System.Collections; using System.Collections.Generic; using UnityEngine;public class Fly : MonoBehaviour {//獲取小鳥&#xff08;剛體&#xff09;private Rigidbod…

【Apipost】批量刪除我的51CTO文章

文章目錄 一、序二、API分析三、Apipost測試四、腳本五、Apipost中完成 一、序 去年開始再51CTO同步更新文章&#xff0c;一年多過去了&#xff0c;只漲了3個粉絲。看了下這個平臺就是賣課、搞培訓的&#xff0c;退出了。決定把文章也刪除了&#xff08;有人私信我說專門注冊了…

ToolkenGPT:用大量工具增強LLM

深度學習自然語言處理 原創作者&#xff1a;cola 用外部工具增強大型語言模型(LLM)已經成為解決復雜問題的一種方法。然而&#xff0c;用樣例數據對LLM進行微調的傳統方法&#xff0c;可能既昂貴又局限于一組預定義的工具。最近的上下文學習范式緩解了這一問題&#xff0c;但有…