Signal emitting a structure - qt

This question is in my mind for many days but i got cleared till now
if i try to send a signal of a structure say
struct radarStruct
{
unsigned char *Data;
unsigned int rate;
unsigned int timeStamp;
float timeSec;
};
shall i emit the signal like
signals:
void radarGeneratorData(const radarStruct &);
or
signals:
void radarGeneratorData(radarStruct *);
More: what about the unsigned char *Data , whether the signal will make a deep copy of it ??
similar for a unsigned char *data how i can send the signal .
Friends please help me clear this , the best way to send a structure through signals & slot mechanism ..
Thnks in advance

This mainly depends on your requirement.
If you want to send the structure over to another object and "share" the structure, you would need to send the structure as a pointer so that changes are reflected at source. If not then you would want to send it as a const ref.
For either methods remember you need to Q_DECLARE_METATYPE(YourStructType) before you can use the structure in signal / slot arguments.
As for when a deep copy occurs / when a routine call back equivalent process happens, you can have a read through
Signaling failure in qt slots
Single Thread communication and Cross-Threaded communication differ within themselves and the output would again depend on your usage.

Related

Good Practice to pass arguments in queued connection

I want an simple and clear example of how to do the signal and slot mechanism in queued connection.
Take the below line as example. Think that obj1 is backend functionality object emitting signal asynchronously from another thread and is connected to a slot in GUI ( main thread):
connect(obj1, SIGNAL(Mysignal(vector<mystruct> )), this, slot(myslot(vector <mystruct>)))
I have read that you have to register the types(meta types).
Please give a clear, simple and ready to use code lines for the above example that I would need, so that errors during run time like vector, my struct or string not defined, etc.. I don't face.
Also, is there a better way to handle this like sending pointers like:
connect(obj1, SIGNAL(Mysignal(obj2 *)), this, slot(myslot(obj2 *)))
Obj2 contains the vector of mystruct. Will i still need to register the obj2 with those metatypes?
If somebody has experience in this, please share all your good practices and simple code snippets, I am new to the queued connections with arguments. Please help.
If you want a queued connection, you need to call connect with a 5. parameter Qt::QueuedConnection. Otherwise, you get a direct connection inside the thread where you sent the signal from. Edit: See Tobys comment below.
You must wrap a QVector<> into a typedef, otherwise registering will not work (bug? in Qt from the stoneage). Also do not use references to your typedef, will not work either.
Header
typedef struct {
int a;
int b;
} mystruct;
typedef QVector<mystruct> myvector;
Q_DECLARE_METATYPE(myvector);
Source
void MainWindow::test()
{
qRegisterMetaType<myvector>();
connect(this, SIGNAL(sigRec(myvector)), SLOT(slotRec(myvector)), Qt::QueuedConnection);
mystruct x = {1,2};
myvector v;
v.append(x);
emit sigRec(v);
}
void MainWindow::slotRec(myvector s)
{
}

What are some best practices for debugging Qt signals and slots?

Debugging signals and slots can be hard, because the debugger does not jump to the slots of a signal when it is emitted. What are some best practices for debugging Qt signals and slots?
In particular
How do I make sure connections are set up successfully?
When should I use signals and slots, when should I avoid them?
What are the most efficient debugging techniques from your experience?
There was a blog post written a while back called 20 ways to debug Qt signals and slots
It addresses I think #1 and #3 of your questions.
For #2, I don't think there is really a hard and fast reason to use or not use signals/slots, as they are a pretty core concept of the GUI framework. Signals are a perfect way to decouple the knowledge of one component to another, allowing you to design reusable widgets that simply declare state changes or notifications. It is also a very good way to communicate GUI changes from non-GUI thread loops, by emitting a signal that the main thread can see.
There might be times where what you really want instead of a signal/slot is to use events, such as when a parent widget should become the event filter for a number of child widgets. The children still do not need to know about the parent, and the parent gets a more direct event as opposed to a signal connection.
On the same topic of events, there are times where what you really want is a bubbling up of an event from child -> parent -> grandparent -> etc. Signals would make less sense here because they are not meant as a way to determine whether the proposed event should result in an action (they could be used this way obviously). Events allow you to check the current state, decide whether this widget should do anything, or otherwise bubble them up the chain for someone else to inspect.
There is a really fantastic answer about The Difference Between Signals/Slots and Events. Here is a good snippet:
You "handle" events
You "get notified of" signal emissions
What I like about that quote is that it describes the different need case. If you need to handle an action in a widget, then you probable want an event. If you want to be notified of things happening, then you probably want a signal.
In addition to what have been said, here are additional tricks.
If you use QTest for your unit tests, then you can pass -vs argument to the executable and all signals will be shown in the console.
I looked at how QTest works, and it registers callbacks that is triggered when signal and slots are executed using QSignalDumper class. However, this API is not exported and might break any time. Here is how I was able to hook on all signals and slots on Linux with Qt 5.10 using GCC.
// QSignalSpyCallbackSet is defined in qt5/qtbase/src/corelib/kernel/qobject_p.h
struct QSignalSpyCallbackSet
{
typedef void (*BeginCallback)(QObject *caller, int signal_or_method_index, void **argv);
typedef void (*EndCallback)(QObject *caller, int signal_or_method_index);
BeginCallback signal_begin_callback,
slot_begin_callback;
EndCallback signal_end_callback,
slot_end_callback;
};
typedef void (*register_spy_callbacks)(const QSignalSpyCallbackSet &callback_set);
static void showObject(QObject *caller, int signal_index, const QString &msg)
{
const QMetaObject *metaObject = caller->metaObject();
QMetaMethod member = metaObject->method(signal_index);
qDebug() << msg << metaObject->className() << qPrintable(member.name());
}
static void onSignalBegin(QObject *caller, int signal_index, void **argv)
{
showObject(caller, signal_index, "onSignalBegin");
}
static void onSlotBegin(QObject *caller, int signal_index, void **argv)
{
showObject(caller, signal_index, "onSlotBegin");
}
int main(int argc, char *argv[])
{
static QSignalSpyCallbackSet set = { onSignalBegin, onSlotBegin, 0, 0 };
QLibrary qtcore("libQt5Core");
register_spy_callbacks reg = (register_spy_callbacks)qtcore.resolve("_Z32qt_register_signal_spy_callbacksRK21QSignalSpyCallbackSet");
if (reg) {
reg(set);
}
...
}
I believe that Qt should expose that API, because we could use it for so many things beyond debugging, such as monitoring the time spent in a slot, get statistics, etc.
How do I make sure connections are set up successfully?
You will see warnings in the console output from your application for each failed connection.
When should I use signals and slots, when should I avoid them?
In my opinion, it's fine to use them any time you want to maintain separation of concerns in your class design. Your class can emit a signal that may or may not be answered by another class (or classes) completely unknown to your class. This keeps your coupling down.
What are the most efficient debugging techniques from your experience?
I can't really add anything more than what is said on this blog post. 20 ways to debug Qt signals and slots
Regarding #1, I'll just add another piece of information that I didn't see mentioned above or in the referenced blog post.
From the documentation on QObject::connect():
Creates a connection of the given type from the signal in the sender object to the method in the receiver object. Returns true if the connection succeeds; otherwise returns false.
I prefer asserting the return value of my connection to make sure the connection succeeded, especially because not all Qt programs will have console output. This also leads to more easily maintainable code, as it will catch changes made at a later date to either the signal or the slot, and force the programmer who made the changes to update the connections as well.

Global Variable Pointer to array in Sourceboost C

I declared these global variables:
volatile unsigned char BUFFER[7]={0,0,0,0,0,0,0};//to get all data
volatile unsigned char *PTR=&BUFFER[0];//points to start address
Inside the Microchip PIC interrupt function, the pointer reads the UART register and deference it to BUFFER[] array according to my code:
*PTR=rcreg;
PTR++;
I then check the data in function main():
for(i=0;i<3;i++){
if(BUFFER[i]==DATA[i]){
k++;
if(k==2){LED_On();}
}
}
and set ptr to point at the start address of BUFFER[]
ptr=BUFFER;
Question: Is this the best way and correct way to read data in the register? How can I use pointer in interrupt function?
Thank you for your kind attention and help in advance!
You may want to consider implementing a lock-free circular buffer to transfer data between the ISR and main():
Circular lock-free buffer
Non-blocking algorithm

Process audio sounds from microphone using Qt

I am developing a sound processing application using Qt as a front end.
How can I get data samples from the microphone? I tried overriding qint64 writeData(const char *data, qint64 len) in QIODevice, but I was unable to get data samples.
Use QAudioInput class.
see : QAudioInput Class ref in Qt Doc

Argument type for Qt signal and slot, does const reference qualifiers matters?

For signal and slot of below type
signals:
void textChanged(const QString &);
public slots:
void setText(const QString & text)
the type of argument of textChanged and setText seems to work invarable of const and &. Does the constant and reference qualification make any difference compared to just using QString ?
QObject::connect(a,SIGNAL(textChanged(QString)),b,SLOT(setText(QString)));
QObject::connect(a,SIGNAL(textChanged(const QString &)),b,SLOT(setText(const QString &)));
EDIT:
I did not notice the output window showing error messages when there is incompatible type being used in SIGNAL or SLOT. I thought the signal slot mechanism is capable of detecting argument type error at compile time.
Qt checks a normalized signature, meaning
Normalization reduces whitespace to a
minimum, moves 'const' to the front
where appropriate, removes 'const'
from value types and replaces const
references with values.
Disclaimer: My qt is rather rusty, but the signal/slot mechanism is still just C++ function calls. If the signal/slot mechanism actually copies objects into internal storage, my apologies (you'll need to check the Qt pages, there's a big one on signals/slots afaik) - as the bits below will only be relevant in a C++ context, not in a C++ + Qt context.
If you leave out the reference, the string will be copied (and having the const would not matter, any changes made to it will remain in the function alone).
If you leave in the reference but take out the const, you allow the method to modify the string that you give it. They both work, but do different things to the object you pass (amount of copying/possibility of retaining changes).
I suggest you read the following resources:
(on const correctness) https://isocpp.org/wiki/faq/const-correctness
(on references) https://isocpp.org/wiki/faq/references
to understand exactly what passing a parameter is and how
void foo(const A&)/
void foo(const A)/
void foo(A&)/
void foo(A)
are all different.

Resources