QSerialPort closed when access from another class
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:
Code:
public:
explicit MainWindow
(QWidget *parent
= 0);
~MainWindow();
QSerialPort *serialport; // Is this the right place for the declaration?
mainwindow.cpp:
Code:
MainWindow
::MainWindow(QWidget *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:
Code:
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.
Re: QSerialPort closed when access from another class
And where is the serialport->open() ?
Re: QSerialPort closed when access from another class
Quote:
And where is the serialport->open() ?
Sorry: I opened it in the mainwindow.pp just under the connect code:
Code:
MainWindow
::MainWindow(QWidget *parent
) : ui(new Ui::MainWindow)
{
serialport = new QSerialPort(this);
connect(serialport, SIGNAL(readyRead()), this, SLOT(main_readData()));
{
showStatusMessage(tr("STATO SISTEMA: OK"));
}
Re: QSerialPort closed when access from another class
Can You show real code ? In the first post you showed some strange pieces of code that do not make sense.
Re: QSerialPort closed when access from another class
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.
Re: QSerialPort closed when access from another class
Quote:
Originally Posted by
d_stranz
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!
Re: QSerialPort closed when access from another class
You can pass the pointer of a QSerialPort object or use the signals and slots mechanism.