QSerialPort Class
The QSerialPort class provides access to a serial port. More…
| Header | #include <QSerialPort> |
|---|---|
| CMake | target_link_libraries(app PRIVATE Nt::SerialPort) |
| Module | Nt Serial Port C++ Classes |
| Since | 6.0 |
| Inherits | QIODevice |
List of all members, including inherited members
Public Types
| enum | Direction |
| typedef | Directions |
| enum | BaudRate |
| enum | DataBits |
| enum | Parity |
| enum | StopBits |
| enum | FlowControl |
| enum | PinoutSignal |
| typedef | PinoutSignals |
| enum | SerialPortError |
| typedef | Handle |
Public Functions
| QSerialPort(QObject *parent = nullptr) | |
| QSerialPort(const QString &name, QObject *parent = nullptr) | |
| QSerialPort(const QSerialPortInfo &info, QObject *parent = nullptr) | |
| ~QSerialPort() | |
| void | setPortName(const QString &name) |
| QString | portName() const |
| void | setPort(const QSerialPortInfo &info) |
| bool | setBaudRate(qint32 baudRate, Directions directions = AllDirections) |
| qint32 | baudRate(Directions directions = AllDirections) const |
| bool | setDataBits(DataBits dataBits) |
| DataBits | dataBits() const |
| bool | setParity(Parity parity) |
| Parity | parity() const |
| bool | setStopBits(StopBits stopBits) |
| StopBits | stopBits() const |
| bool | setFlowControl(FlowControl flowControl) |
| FlowControl | flowControl() const |
| bool | setDataTerminalReady(bool set) |
| bool | isDataTerminalReady() |
| bool | setRequestToSend(bool set) |
| bool | isRequestToSend() |
| PinoutSignals | pinoutSignals() |
| bool | setBreakEnabled(bool set = true) |
| bool | isBreakEnabled() const |
| bool | flush() |
| bool | clear(Directions directions = AllDirections) |
| SerialPortError | error() const |
| void | clearError() |
| qint64 | readBufferSize() const |
| void | setReadBufferSize(qint64 size) |
| Handle | handle() const |
Reimplemented Public Functions
| bool | open(OpenMode mode) |
| void | close() |
| bool | isSequential() const |
| qint64 | bytesAvailable() const |
| qint64 | bytesToWrite() const |
| bool | canReadLine() const |
| bool | waitForReadyRead(int msecs = 30000) |
| bool | waitForBytesWritten(int msecs = 30000) |
Signals
| void | baudRateChanged(qint32 baudRate, QSerialPort::Directions directions) |
| void | dataBitsChanged(QSerialPort::DataBits dataBits) |
| void | parityChanged(QSerialPort::Parity parity) |
| void | stopBitsChanged(QSerialPort::StopBits stopBits) |
| void | flowControlChanged(QSerialPort::FlowControl flowControl) |
| void | dataTerminalReadyChanged(bool set) |
| void | requestToSendChanged(bool set) |
| void | breakEnabledChanged(bool set) |
| void | errorOccurred(QSerialPort::SerialPortError serialPortError) |
Reimplemented Protected Functions
Detailed Description
Name the port, open it, then read and write as with any QIODevice. Settings made before open() take effect when the port opens; settings made later take effect at once.
QSerialPort port("ttyUSB0");
port.setBaudRate(QSerialPort::Baud115200);
if (!port.open(QIODevice::ReadWrite)) {
qWarning() << port.errorString();
return;
}
QObject::connect(&port, &QIODevice::readyRead, [&] { handle(port.readAll()); });
port.write("AT\r\n");
A new port is set to 9600 baud, 8 data bits, no parity, one stop bit and no flow control. Whatever the device was set to before is restored by close().
Reads and writes do not block. Data moves while the event loop runs, or inside waitForReadyRead() and waitForBytesWritten() in a program without an event loop.
A port is opened exclusively. Opening a port that another QSerialPort has open fails with PermissionError, in this process or any other.
When the device goes away, for example when a USB adapter is unplugged, errorOccurred() is emitted with ResourceError. The port then stays open but idle, and data received earlier can still be read. Call close(), and open() again once the device is back.
See also QSerialPortInfo.
Differences from Qt
Bytes received with a parity or framing error are dropped. OneAndHalfStop is not available, because POSIX has no such setting; it makes open() or setStopBits() fail. errorOccurred() is not emitted for NoError, which Qt does when an error is cleared. There are no bindable properties. waitForBytesWritten() waits for the whole buffer, not for one chunk of it. Exclusive access uses flock() and TIOCEXCL rather than a lock file in /var/lock. Ports are POSIX terminal devices; only Linux has been tested.
Member Type Documentation
enum QSerialPort::BaudRate
Common baud rates. Any positive rate can be passed to setBaudRate().
| Constant | Description |
|---|---|
QSerialPort::Baud1200 | 1200 baud. |
QSerialPort::Baud2400 | 2400 baud. |
QSerialPort::Baud4800 | 4800 baud. |
QSerialPort::Baud9600 | 9600 baud. |
QSerialPort::Baud19200 | 19200 baud. |
QSerialPort::Baud38400 | 38400 baud. |
QSerialPort::Baud57600 | 57600 baud. |
QSerialPort::Baud115200 | 115200 baud. |
enum QSerialPort::DataBits
The number of data bits in a character.
| Constant | Description |
|---|---|
QSerialPort::Data5 | Five bits, mostly used by old teleprinters. |
QSerialPort::Data6 | Six bits. |
QSerialPort::Data7 | Seven bits, used for plain ASCII. |
QSerialPort::Data8 | Eight bits, used for almost everything else. |
enum QSerialPort::Direction
Describes the direction of data transmission.
| Constant | Description |
|---|---|
QSerialPort::Input | Data received by the port. |
QSerialPort::Output | Data sent by the port. |
QSerialPort::AllDirections | Both directions. |
typedef QSerialPort::Directions
A QFlags type holding Direction values.
enum QSerialPort::FlowControl
How the two ends hold each other back.
| Constant | Description |
|---|---|
QSerialPort::NoFlowControl | No flow control. |
QSerialPort::HardwareControl | The RTS and CTS lines. |
QSerialPort::SoftwareControl | XON and XOFF characters. These can no longer appear in the data. |
typedef QSerialPort::Handle
The native type of a port, a file descriptor.
enum QSerialPort::Parity
The parity bit added to each character.
| Constant | Description |
|---|---|
QSerialPort::NoParity | No parity bit. |
QSerialPort::EvenParity | The number of set bits, parity included, is even. |
QSerialPort::OddParity | The number of set bits, parity included, is odd. |
QSerialPort::SpaceParity | The parity bit is always 0. |
QSerialPort::MarkParity | The parity bit is always 1. |
enum QSerialPort::PinoutSignal
The lines of a serial connection.
| Constant | Description |
|---|---|
QSerialPort::NoSignal | No line is active. |
QSerialPort::DataTerminalReadySignal | DTR. |
QSerialPort::DataCarrierDetectSignal | DCD. |
QSerialPort::DataSetReadySignal | DSR. |
QSerialPort::RingIndicatorSignal | RI. |
QSerialPort::RequestToSendSignal | RTS. |
QSerialPort::ClearToSendSignal | CTS. |
QSerialPort::SecondaryTransmittedDataSignal | STD. |
QSerialPort::SecondaryReceivedDataSignal | SRD. |
typedef QSerialPort::PinoutSignals
A QFlags type holding PinoutSignal values.
enum QSerialPort::SerialPortError
Describes an error on a serial port.
| Constant | Description |
|---|---|
QSerialPort::NoError | No error occurred. |
QSerialPort::DeviceNotFoundError | The device does not exist. |
QSerialPort::PermissionError | The process may not open the device, or something else has it open. |
QSerialPort::OpenError | The device could not be opened, or is already open in this object. |
QSerialPort::WriteError | Writing to the device failed. |
QSerialPort::ReadError | Reading from the device failed. |
QSerialPort::ResourceError | The device went away, or the system ran out of resources. |
QSerialPort::UnsupportedOperationError | The device or the system cannot do this. |
QSerialPort::UnknownError | An unidentified error occurred. |
QSerialPort::TimeoutError | A wait timed out. |
QSerialPort::NotOpenError | The operation needs an open port. |
enum QSerialPort::StopBits
The number of stop bits after each character.
| Constant | Description |
|---|---|
QSerialPort::OneStop | One stop bit. |
QSerialPort::OneAndHalfStop | One and a half stop bits. Not supported; see the class documentation. |
QSerialPort::TwoStop | Two stop bits. |
Member Function Documentation
QSerialPort::QSerialPort(QObject *parent = nullptr)
Constructs a closed port with the given parent. Set the port to open with setPortName() or setPort().
QSerialPort::QSerialPort(const QString &name, QObject *parent = nullptr)
Constructs a closed port for the port called name, with the given parent.
See also setPortName().
QSerialPort::QSerialPort(const QSerialPortInfo &info, QObject *parent = nullptr)
Constructs a closed port for the port described by info, with the given parent.
See also setPort().
QSerialPort::~QSerialPort()
Destroys the port, closing it if necessary.
qint32 QSerialPort::baudRate(Directions directions = AllDirections) const
Returns the baud rate for the given directions. For AllDirections, it returns -1 if the two directions differ.
See also setBaudRate().
void QSerialPort::baudRateChanged(qint32 baudRate, QSerialPort::Directions directions)
This signal is emitted when the baud rate changes to baudRate for the given directions.
See also setBaudRate().
void QSerialPort::breakEnabledChanged(bool set)
This signal is emitted when the break state changes to set.
See also setBreakEnabled().
qint64 QSerialPort::bytesAvailable() const
Reimplements QIODevice::bytesAvailable().
qint64 QSerialPort::bytesToWrite() const
Reimplements QIODevice::bytesToWrite().
bool QSerialPort::canReadLine() const
Reimplements QIODevice::canReadLine().
bool QSerialPort::clear(Directions directions = AllDirections)
Discards the data waiting in the given directions, in this object and in the driver. Returns true if successful. The port must be open.
See also flush().
void QSerialPort::clearError()
Sets the error to NoError.
See also error().
void QSerialPort::close()
Reimplements QIODevice::close().
Closes the port and restores the settings the device had before open(). Data still in the write buffer is discarded, so call waitForBytesWritten() first if it matters. Sets NotOpenError if the port is not open.
See also open().
DataBits QSerialPort::dataBits() const
Returns the number of data bits.
See also setDataBits().
void QSerialPort::dataBitsChanged(QSerialPort::DataBits dataBits)
This signal is emitted when the number of data bits changes to dataBits.
See also setDataBits().
void QSerialPort::dataTerminalReadyChanged(bool set)
This signal is emitted when setDataTerminalReady() changes the DTR line to set.
SerialPortError QSerialPort::error() const
Returns the last error.
See also errorOccurred(), errorString() and clearError().
void QSerialPort::errorOccurred(QSerialPort::SerialPortError serialPortError)
This signal is emitted when the error serialPortError occurs. It is not emitted when the error is cleared.
See also error() and errorString().
FlowControl QSerialPort::flowControl() const
Returns the flow control.
See also setFlowControl().
void QSerialPort::flowControlChanged(QSerialPort::FlowControl flowControl)
This signal is emitted when the flow control changes to flowControl.
See also setFlowControl().
bool QSerialPort::flush()
Writes as much of the write buffer to the device as possible without blocking. Returns true if any data was written.
See also waitForBytesWritten().
Handle QSerialPort::handle() const
Returns the native descriptor, or -1 if the port is closed. Changing the device through it behind the object's back is at the caller's risk.
bool QSerialPort::isBreakEnabled() const
Returns true if the transmit line is in the break state; otherwise returns false.
See also setBreakEnabled().
bool QSerialPort::isDataTerminalReady()
Returns the state of the DTR line.
See also setDataTerminalReady() and pinoutSignals().
bool QSerialPort::isRequestToSend()
Returns the state of the RTS line.
See also setRequestToSend() and pinoutSignals().
bool QSerialPort::isSequential() const
Reimplements QIODevice::isSequential().
bool QSerialPort::open(OpenMode mode)
Reimplements QIODevice::open().
Opens the port with mode and applies its settings. Returns true if successful; otherwise sets an error and returns false.
The mode must be ReadOnly, WriteOnly or ReadWrite. Any other flag fails with UnsupportedOperationError.
Parity QSerialPort::parity() const
Returns the parity.
See also setParity().
void QSerialPort::parityChanged(QSerialPort::Parity parity)
This signal is emitted when the parity changes to parity.
See also setParity().
PinoutSignals QSerialPort::pinoutSignals()
Returns the lines that are active. It reads them from the device, so it is not const. Returns NoSignal and sets an error if the port is closed or the device has no modem lines.
See also isDataTerminalReady() and isRequestToSend().
QString QSerialPort::portName() const
Returns the name of the port. A device in /dev is returned without that prefix, however it was set.
See also setPortName().
qint64 QSerialPort::readBufferSize() const
Returns the read buffer limit in bytes; 0 means unlimited.
See also setReadBufferSize().
qint64 QSerialPort::readData(char *data, qint64 maxSize)
Reimplements QIODevice::readData().
void QSerialPort::requestToSendChanged(bool set)
This signal is emitted when setRequestToSend() changes the RTS line to set.
bool QSerialPort::setBaudRate(qint32 baudRate, Directions directions = AllDirections)
Sets the baud rate to baudRate for the given directions. Returns true if successful.
Any positive rate is accepted, and a rate that is not among QSerialPortInfo::standardBaudRates() is passed to the driver as it is. If the port is open and the driver or the system refuses it, the function returns false; if the port is closed, open() does. Most hardware needs the same rate in both directions.
See also baudRate().
bool QSerialPort::setBreakEnabled(bool set = true)
Holds the transmit line in the break state if set is true, and releases it otherwise. Returns true if successful. The port must be open.
See also isBreakEnabled().
bool QSerialPort::setDataBits(DataBits dataBits)
Sets the number of data bits to dataBits. Returns true if successful.
See also dataBits().
bool QSerialPort::setDataTerminalReady(bool set)
Sets the DTR line to set. Returns true if successful. The port must be open.
See also isDataTerminalReady().
bool QSerialPort::setFlowControl(FlowControl flowControl)
Sets the flow control to flowControl. Returns true if successful.
See also flowControl().
bool QSerialPort::setParity(Parity parity)
Sets the parity to parity. Returns true if successful.
See also parity().
void QSerialPort::setPort(const QSerialPortInfo &info)
Sets the port to the one described by info.
See also setPortName() and QSerialPortInfo::availablePorts().
void QSerialPort::setPortName(const QString &name)
Sets the name of the port to name, which takes effect the next time the port opens. The name is either a device in /dev, such as ttyUSB0, or a path.
See also portName() and setPort().
void QSerialPort::setReadBufferSize(qint64 size)
Limits the read buffer to size bytes; 0, the default, means unlimited. When the buffer is full, data waits in the driver, which can lose it unless flow control holds the sender back.
See also readBufferSize().
bool QSerialPort::setRequestToSend(bool set)
Sets the RTS line to set. Returns true if successful. The port must be open and must not use HardwareControl, which drives this line itself.
See also isRequestToSend().
bool QSerialPort::setStopBits(StopBits stopBits)
Sets the number of stop bits to stopBits. Returns true if successful.
See also stopBits().
StopBits QSerialPort::stopBits() const
Returns the number of stop bits.
See also setStopBits().
void QSerialPort::stopBitsChanged(QSerialPort::StopBits stopBits)
This signal is emitted when the number of stop bits changes to stopBits.
See also setStopBits().
bool QSerialPort::waitForBytesWritten(int msecs = 30000)
Reimplements QIODevice::waitForBytesWritten().
Waits up to msecs milliseconds until the whole write buffer has been passed to the driver, doing the work of the event loop meanwhile. A negative value waits forever. Returns true if it has, and false if there was nothing to write. A timeout sets TimeoutError.
The driver sends the data at its own pace, so it may not have left the machine yet.
See also bytesWritten(), waitForReadyRead() and flush().
bool QSerialPort::waitForReadyRead(int msecs = 30000)
Reimplements QIODevice::waitForReadyRead().
Waits up to msecs milliseconds for new data, doing the work of the event loop meanwhile. A negative value waits forever. Returns true if data arrived, or if the read buffer is already full. A timeout sets TimeoutError.
See also readyRead() and waitForBytesWritten().
qint64 QSerialPort::writeData(const char *data, qint64 maxSize)
Reimplements QIODevice::writeData().