#include <QTextStream>
#include <QCoreApplication>
#include <QtSerialPort/QSerialPortInfo>
QT_USE_NAMESPACE
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QTextStream out(stdout);
const auto serialPortInfos = QSerialPortInfo::availablePorts();
out << QObject::tr("Total number of ports available: ") << serialPortInfos.count() << endl;
const QString blankString = QObject::tr("N/A");
QString description;
QString manufacturer;
QString serialNumber;
for (const QSerialPortInfo &serialPortInfo : serialPortInfos) {
description = serialPortInfo.description();
manufacturer = serialPortInfo.manufacturer();
serialNumber = serialPortInfo.serialNumber();
out << endl
<< QObject::tr("Port: ") << serialPortInfo.portName() << endl
<< QObject::tr("Location: ") << serialPortInfo.systemLocation() << endl
<< QObject::tr("Description: ") << (!description.isEmpty() ? description : blankString) << endl
<< QObject::tr("Manufacturer: ") << (!manufacturer.isEmpty() ? manufacturer : blankString) << endl
<< QObject::tr("Serial number: ") << (!serialNumber.isEmpty() ? serialNumber : blankString) << endl
<< QObject::tr("Vendor Identifier: ") << (serialPortInfo.hasVendorIdentifier() ? QByteArray::number(serialPortInfo.vendorIdentifier(), 16) : blankString) << endl
<< QObject::tr("Product Identifier: ") << (serialPortInfo.hasProductIdentifier() ? QByteArray::number(serialPortInfo.productIdentifier(), 16) : blankString) << endl
<< QObject::tr("Busy: ") << (serialPortInfo.isBusy() ? QObject::tr("Yes") : QObject::tr("No")) << endl;
}
return 0;
}
另一个显示UI的例子,QLabel可以使用QString实例化。
#include <QApplication>
#include <QWidget>
#include <QVBoxLayout>
#include <QLabel>
#include <QScrollArea>
#include <QtSerialPort/QSerialPortInfo>
QT_USE_NAMESPACE
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QVBoxLayout *layout = new QVBoxLayout;
const auto infos = QSerialPortInfo::availablePorts();
for (const QSerialPortInfo &info : infos) {
QString s = QObject::tr("Port: ") + info.portName() + "\n"
+ QObject::tr("Location: ") + info.systemLocation() + "\n"
+ QObject::tr("Description: ") + info.description() + "\n"
+ QObject::tr("Manufacturer: ") + info.manufacturer() + "\n"
+ QObject::tr("Serial number: ") + info.serialNumber() + "\n"
+ QObject::tr("Vendor Identifier: ") + (info.hasVendorIdentifier() ? QString::number(info.vendorIdentifier(), 16) : QString()) + "\n"
+ QObject::tr("Product Identifier: ") + (info.hasProductIdentifier() ? QString::number(info.productIdentifier(), 16) : QString()) + "\n"
+ QObject::tr("Busy: ") + (info.isBusy() ? QObject::tr("Yes") : QObject::tr("No")) + "\n";
QLabel *label = new QLabel(s);
layout->addWidget(label);
}
QWidget *workPage = new QWidget;
workPage->setLayout(layout);
QScrollArea area;
area.setWindowTitle(QObject::tr("Info about all available serial ports."));
area.setWidget(workPage);
area.show();
return a.exec();
}