6.0.0-rc4Source

QSerialPort Class

The QSerialPort class provides access to a serial port. More…

Header#include <QSerialPort>
CMaketarget_link_libraries(app PRIVATE Nt::SerialPort)
ModuleNt Serial Port C++ Classes
Since6.0
InheritsQIODevice

List of all members, including inherited members

Public Types

Public Functions

QSerialPort(QObject *parent = nullptr)
QSerialPort(const QString &name, QObject *parent = nullptr)
QSerialPort(const QSerialPortInfo &info, QObject *parent = nullptr)
~QSerialPort()
voidsetPortName(const QString &name)
QStringportName() const
voidsetPort(const QSerialPortInfo &info)
boolsetBaudRate(qint32 baudRate, Directions directions = AllDirections)
qint32baudRate(Directions directions = AllDirections) const
boolsetDataBits(DataBits dataBits)
DataBitsdataBits() const
boolsetParity(Parity parity)
Parityparity() const
boolsetStopBits(StopBits stopBits)
StopBitsstopBits() const
boolsetFlowControl(FlowControl flowControl)
FlowControlflowControl() const
boolsetDataTerminalReady(bool set)
boolisDataTerminalReady()
boolsetRequestToSend(bool set)
boolisRequestToSend()
PinoutSignalspinoutSignals()
boolsetBreakEnabled(bool set = true)
boolisBreakEnabled() const
boolflush()
boolclear(Directions directions = AllDirections)
SerialPortErrorerror() const
voidclearError()
qint64readBufferSize() const
voidsetReadBufferSize(qint64 size)
Handlehandle() const

Reimplemented Public Functions

boolopen(OpenMode mode)
voidclose()
boolisSequential() const
qint64bytesAvailable() const
qint64bytesToWrite() const
boolcanReadLine() const
boolwaitForReadyRead(int msecs = 30000)
boolwaitForBytesWritten(int msecs = 30000)

Signals

Reimplemented Protected Functions

qint64readData(char *data, qint64 maxSize)
qint64writeData(const char *data, qint64 maxSize)

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().

ConstantDescription
QSerialPort::Baud12001200 baud.
QSerialPort::Baud24002400 baud.
QSerialPort::Baud48004800 baud.
QSerialPort::Baud96009600 baud.
QSerialPort::Baud1920019200 baud.
QSerialPort::Baud3840038400 baud.
QSerialPort::Baud5760057600 baud.
QSerialPort::Baud115200115200 baud.

enum QSerialPort::DataBits

The number of data bits in a character.

ConstantDescription
QSerialPort::Data5Five bits, mostly used by old teleprinters.
QSerialPort::Data6Six bits.
QSerialPort::Data7Seven bits, used for plain ASCII.
QSerialPort::Data8Eight bits, used for almost everything else.

enum QSerialPort::Direction

Describes the direction of data transmission.

ConstantDescription
QSerialPort::InputData received by the port.
QSerialPort::OutputData sent by the port.
QSerialPort::AllDirectionsBoth directions.

typedef QSerialPort::Directions

A QFlags type holding Direction values.

enum QSerialPort::FlowControl

How the two ends hold each other back.

ConstantDescription
QSerialPort::NoFlowControlNo flow control.
QSerialPort::HardwareControlThe RTS and CTS lines.
QSerialPort::SoftwareControlXON 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.

ConstantDescription
QSerialPort::NoParityNo parity bit.
QSerialPort::EvenParityThe number of set bits, parity included, is even.
QSerialPort::OddParityThe number of set bits, parity included, is odd.
QSerialPort::SpaceParityThe parity bit is always 0.
QSerialPort::MarkParityThe parity bit is always 1.

enum QSerialPort::PinoutSignal

The lines of a serial connection.

ConstantDescription
QSerialPort::NoSignalNo line is active.
QSerialPort::DataTerminalReadySignalDTR.
QSerialPort::DataCarrierDetectSignalDCD.
QSerialPort::DataSetReadySignalDSR.
QSerialPort::RingIndicatorSignalRI.
QSerialPort::RequestToSendSignalRTS.
QSerialPort::ClearToSendSignalCTS.
QSerialPort::SecondaryTransmittedDataSignalSTD.
QSerialPort::SecondaryReceivedDataSignalSRD.

typedef QSerialPort::PinoutSignals

A QFlags type holding PinoutSignal values.

enum QSerialPort::SerialPortError

Describes an error on a serial port.

ConstantDescription
QSerialPort::NoErrorNo error occurred.
QSerialPort::DeviceNotFoundErrorThe device does not exist.
QSerialPort::PermissionErrorThe process may not open the device, or something else has it open.
QSerialPort::OpenErrorThe device could not be opened, or is already open in this object.
QSerialPort::WriteErrorWriting to the device failed.
QSerialPort::ReadErrorReading from the device failed.
QSerialPort::ResourceErrorThe device went away, or the system ran out of resources.
QSerialPort::UnsupportedOperationErrorThe device or the system cannot do this.
QSerialPort::UnknownErrorAn unidentified error occurred.
QSerialPort::TimeoutErrorA wait timed out.
QSerialPort::NotOpenErrorThe operation needs an open port.

enum QSerialPort::StopBits

The number of stop bits after each character.

ConstantDescription
QSerialPort::OneStopOne stop bit.
QSerialPort::OneAndHalfStopOne and a half stop bits. Not supported; see the class documentation.
QSerialPort::TwoStopTwo stop bits.

Member Function Documentation

[explicit] QSerialPort::QSerialPort(QObject *parent = nullptr)

Constructs a closed port with the given parent. Set the port to open with setPortName() or setPort().

[explicit] QSerialPort::QSerialPort(const QString &name, QObject *parent = nullptr)

Constructs a closed port for the port called name, with the given parent.

See also setPortName().

[explicit] 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().

[override] 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().

[signal] 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().

[signal] void QSerialPort::breakEnabledChanged(bool set)

This signal is emitted when the break state changes to set.

See also setBreakEnabled().

[override] qint64 QSerialPort::bytesAvailable() const

Reimplements QIODevice::bytesAvailable().

[override] qint64 QSerialPort::bytesToWrite() const

Reimplements QIODevice::bytesToWrite().

[override] 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().

[override] 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().

[signal] void QSerialPort::dataBitsChanged(QSerialPort::DataBits dataBits)

This signal is emitted when the number of data bits changes to dataBits.

See also setDataBits().

[signal] 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().

[signal] 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().

[signal] 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().

[override] bool QSerialPort::isSequential() const

Reimplements QIODevice::isSequential().

[override] 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.

See also close() and error().

Parity QSerialPort::parity() const

Returns the parity.

See also setParity().

[signal] 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().

[override, protected] qint64 QSerialPort::readData(char *data, qint64 maxSize)

Reimplements QIODevice::readData().

[signal] 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().

[signal] void QSerialPort::stopBitsChanged(QSerialPort::StopBits stopBits)

This signal is emitted when the number of stop bits changes to stopBits.

See also setStopBits().

[override] 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().

[override] 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().

[override, protected] qint64 QSerialPort::writeData(const char *data, qint64 maxSize)

Reimplements QIODevice::writeData().