PDA

View Full Version : QSerialPort closed when access from another class



Cazzaniga
4th July 2018, 15:01
Hi,
In a Qt 5 application I need to access the QSerialPort from a class/form different from the one in which the serialport is declared. In other words, In my MainWindow I have:
mainwindow.h:

public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
QSerialPort *serialport; // Is this the right place for the declaration?
mainwindow.cpp:

MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
serialport = new QSerialPort(this);
connect(serialport, SIGNAL(readyRead()), this, SLOT(main_readData()));
...
Now, I need to write data through the serialport from another class:
serial.cpp:

QByteArray ba;
ba.resize(50);
...
MainWindow m;
const qint64 bytesWritten = m.serialport->write(ba);
The problem is: no errors during the build, but when the "write" function is called, the following error appears:
"Permission error while locking the device", and the output console says: "QIODevice::write (QSerialPort): device not open".
It seems like the serialport is close when it is called from a class or form that is not the MainWindow.
How can I have the serialport accessible from everywhere?
How can I fix it? Anyone could give any advice?
Thank you.

Lesiok
5th July 2018, 07:13
And where is the serialport->open() ?

Cazzaniga
5th July 2018, 07:30
And where is the serialport->open() ?
Sorry: I opened it in the mainwindow.pp just under the connect code:


MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
serialport = new QSerialPort(this);
connect(serialport, SIGNAL(readyRead()), this, SLOT(main_readData()));
if (serialport->open(QIODevice::ReadWrite))
{
showStatusMessage(tr("STATO SISTEMA: OK"));
}

Lesiok
5th July 2018, 09:34
Can You show real code ? In the first post you showed some strange pieces of code that do not make sense.

d_stranz
5th July 2018, 21:48
If the original code fragment posted is part of the real code, then the line "MainWindow m;" is creating a new second instance of MainWindow on the stack and is trying to use the QSerialPort that was previously created and opened in the first MainWindow instance.

Cazzaniga
6th July 2018, 08:01
If the original code fragment posted is part of the real code, then the line "MainWindow m;" is creating a new second instance of MainWindow on the stack and is trying to use the QSerialPort that was previously created and opened in the first MainWindow instance.

I see.. so which should be the best way to call a method/function defined in another class without calling a second instance of that class (like I did before)?
Thank you!

Lesiok
6th July 2018, 09:07
You can pass the pointer of a QSerialPort object or use the signals and slots mechanism.