I ran into a problem that I need to keep the mapped source signal's parameters. So far I only found examples to map signals without any parameter.
For example, the clicked() signal:
signalMapper = new QSignalMapper(this);
signalMapper->setMapping(taxFileButton, QString("taxfile.txt"));
connect(taxFileButton, SIGNAL(clicked()),
signalMapper, SLOT (map()));
connect(signalMapper, SIGNAL(mapped(QString)),
this, SLOT(readFile(QString)));
However, I would need to map some signal with its own parameters, for example the clicked(bool) signal, then the SLOT need to have two arguments doStuff(bool,QString):
connect(taxFileButton, SIGNAL(clicked(bool)),
signalMapper, SLOT (map()));
connect(signalMapper, SIGNAL(mapped(QString)),
this, SLOT(doStuff(bool,QString)));
However, it does not work like this? Is there any work around?
Thanks!
QSignalMapper does not provide functionality to pass signal parameters.
see documentation:
This class collects a set of parameterless signals, and re-emits them with integer, string or widget parameters corresponding to the object that sent the signal.
There are the ways to solve that:
If Qt4 is used then I'd suggest to implement your own signal mapper which supports parameters what you need.
QSignalMapper implementation would be good example to start.
But if Qt5 is used then you can do exactly what you need without usage QSignalMapper at all. Just connect signal to lambda:
connect(taxFileButton, &TaxFileButton::clicked, [this](bool arg) {
doStuff(arg, "taxfile.txt");
} );
I assume taxFileButton is instance of TaxFileButton class.
If C++11 lambda is not suitable for some reason then tr1::bind could be used to bind this and "taxfile.txt" values.
Please note such connection will not be disconnected automatically when this object is destroyed.
More details are here.
Related
I want to connect a function to a slot and this is my code.
I get error that no instance of overloaded function matched the argument list.
connect(lineEditCommandInterface, &QLineEdit::textChanged, this, &SUMMIT::ReceiveCommand);
the issue is that ReceiveCommand is a overloaded function and i want to use the function with no arguments.
void ReceiveCommand();
void ReceiveCommand( std::string stdstrCommand);
One possible solution is to use a lambda function:
connect(lineEditCommandInterface, &QLineEdit::textChanged, [this](){
ReceiveCommand();
});
Aanother option could be static casting the slot, just in case you may skip the lambda....
slots:
void fooSlot(int x);
void fooSlot(const QString& n);
then
connect(someObject, &SomeClass::someSignal, this, static_cast<void(MainWindow::*)(const QString&)>(&MainWindow::fooSlot));
connect(someObject, &SomeClass::someSignal, this, static_cast<void(MainWindow::*)(int)>(&MainWindow::fooSlot));
Since Qt 5.6, the recommended (or at least less verbose) way to connect to overloaded signals/slots is with QOverload::of() (which isn't well documented). With Qt 5.7+ and C++14 one can also use qOverload() and friends. Though this doesn't help with mismatched signal/slot parameters, it seems worth pointing out.
Example with C++11 and QOverload:
connect(object, &SomeClass::someSignal, this, QOverload<void>::of(&SUMMIT::ReceiveCommand));
The various options are documented with examples (including the old static_cast method) in: Selecting Overloaded Signals and Slots
Also of possible interest in regards to this question is the section in the same doc: Using Default Parameters in Slots to Connect to Signals with Fewer Parameters. The lambda option is also documented higher up on that page.
Further examples of using QOverload can be found in Qt docs for just about every overloaded signal, (eg. SpinBox::valueChanged()) but it also works for slots.
I'm a beginner in Qt and trying to understand the SIGNAL and SLOT macros. When I'm learning to use the connect method to bind the signal and slot, I found the tutorials on Qt's official reference page uses:
connect(obj1, SIGNAL(signal(int)), obj2, SLOT(slot()))
However, this also works very well:
connect(obj1, &Obj1::signal, obj2, &Obj2::slot)
So what exactly do the macros SIGNAL and SLOT do? Do they just look for the signal in the class the object belongs to and return the address of it?
Then why do most programmers use these macros instead of using &Obj1::signal since the latter appears to be simpler and you don't need to change the code if the parameters of the signal function change?
The use of the SIGNAL and SLOT macros used to be the only way to make connections, before Qt 5. The connection is made at runtime and require signal and slots to be marked in the header. For example:
Class MyClass : public QObject
{
Q_OBJECT
signals:
void Signal();
slots:
void ASlotFunction();
};
To avoid repetition, the way in which it works is described in the QT 4 documentation.
The signal and slot mechanism is part of the C++ extensions that are provided by Qt and make use of the Meta Object Compiler (moc).
This explains why signals and slots use the moc.
The second connect method is much improved as the functions specified can be checked at the time of compilation, not runtime. In addition, by using the address of a function, you can refer to any class function, not just those in the section marked slots:
The documentation was updated for Qt 5.
In addition, there's a good blog post about the Qt 4 connect workings here and Qt 5 here.
Addition to the first answer.
what exactly did the macro SIGNAL and SLOT do
Almost nothing. Look at the qobjectdefs.h:
# define SLOT(a) "1"#a
# define SIGNAL(a) "2"#a
It just adds 1 or 2. It means that next code is valid and works as expected:
QObject *obj = new QObject;
connect(obj,"2objectNameChanged(QString)",this,"1show()");//suppose this is a pointer to a QDialog subclass
obj->setObjectName("newNAme");
why do most programmers use these macros instead of using like
&Obj1::signal
Because these macros work not only in Qt5.
Because with these macros there is no complexity with overloaded
signals (it can make your code very dirty and it is really not a simple thing)
Because with new syntax you sometimes need to use specific
disconnects
More details here.
To complete TheDarkKnight's answer, it is an excellent practice to refactor legacy code that is using the old Qt 4 SIGNAL and SLOT macros to Qt 5's new syntax using function address.
Suddenly, connection error will appear at compile time instead of at runtime! It's very easy to make a Qt 4 connection error as any spelling mistake will result in such an error. Plus, the name of the function must be the fully qualified name, i.e preceded with the full namespace if any.
Another benefit is the ability to use a lambda for the slot function, which can reduce need of a named function if the slot body is trivial.
These macros just convert their parameters to signal/slot-specific strings. The Differences between String-Based and Functor-Based Connections can be found in the docs. In short:
String-based:
Type checking is done at Run-time
Can connect signals to slots which have more arguments than the signal (using default parameters)
Can connect C++ functions to QML functions
Functor-based:
Type checking is done at Compile-time
Can perform implicit type conversions
Can connect signals to lambda expressions
I'm using the next line in order to display the position of the slider on the label.
connect(slider, SIGNAL(valueChanged(int)), label, SLOT(setNum(int)));
It works fine.
However, I don't really understand how is this value being transferred.
How does the parameter of the valueChanged function pass to the setNum function ?
When you call connect you specify a signature of a signal and of a slot (or another signal).
Qt uses these signatures to store an "internal link" between 2 methods.
When a signal method is called (for example, with emit valueChanged(5)) Qt looks for a corresponding slot method in the list of "links".
Then Qt calls a slot method passing arguments from the first signal method.
Read this article thoroughly. It's really awesome.
Every time the signal is triggered, it gives the int to the slot function. It's like if you (the slot) go and see you neighbor to give him eggs and then he do whatever he wants with it.
You can see this excellent doc about how Qt Signals and Slots works
Qt4.8.5
QObject::connect(button,SIGNAL(clicked()),label,SLOT(setText("dd"));
The Qt Creator tell me It's wrong . What's the problem ?
That you can't pass arguments in a connect() statement. You need a "trampoline" slot that sets the text of your label (or, in Qt 5, you might choose to use a lambda).
For instance, by using a subclass:
class MyLabel : public QLabel {
Q_OBJECT
public slots:
void setTextToFoo() { setText("foo"); }
};
// ...
connect(button,SIGNAL(clicked()),label,SLOT(setTextToFoo());
It depends what exactly you are trying to achieve, to be honest, the example code you provided is not very functional, is "dd" a particular static value you are using, or potentially some other string? Where does it come from, is it in the scope of the called, or is it sent by the caller, which is the usual practice when sending arguments to slots.
Either way, in order to make a connect statement the first requirement is for the arguments to match, clicked() has no arguments while setText() has one, so there is a mismatch. As of how to resolve that mismatch, the easiest way is to use simple wrappers, although you can use a QSignalMapper and as of Qt5, lambdas and std::bind.
For starters, you cannot specify the actual argument instance in the connect statement, even with arguments on both sides you only need to specify the types to help resolve overloads (it is terrible with the new connection syntax in Qt5), and not any actual identifiers or literals.
In case of the more usual scenario, where the data is send to the slot by the caller, the identifier or literal is specified in the emit signal(value) statement. Since you don't have clicked(const QString &) you need a wrapper slot that you connect to clicked() and emit with the value in that wrapper slot, or subclass the button and add your own overload of clicked(QString).
In case the value is in the scope of the called, then subclassing doesn't make much sense, all you need is the wrapper slot in the scope of the called object.
If you want more, you will have to use Qt 5, whose syntax is significantly more powerful.
If the question is whats wrong, just remember the parameter number must be the same for the Signal and the Slot. Asking a collegue and according the Peppe, setText(QString) wait for One parameter and the Clicked() is empty...A custom slot is to call the setText() method indirectly.
You can look that : http://qt-project.org/doc/qt-4.8/widgets-calculator.html
It uses the QWidget, an important part of Qt interfaces beside QML.
I'm trying to get the information of several of a class' member variables on the receiving end of a slot/signal setup, so I'd like to pass the entire class through. Unfortunately, after the class has been passed, the member variables seem to be empty. Here's some code snippets:
This sets up the signal to pass the class
signals:
void selected(const ControlIcon *controlIcon);
this is the slot/signal connection
connect(controllerList->serialController, SIGNAL(selected(const ControlIcon*)),
infoView, SLOT(serialControllerSelected(const ControlIcon*)));
I emit the signal from within the class to be passed
emit selected(this);
Here's the code to call on the class' member data
QLabel *ASCIIStringHolder = new QLabel;
ASCIIStringHolder->setText(controlIcon->m_ASCIIString);
Nothing shows up in the label, and when I set a breakpoint, I can see that there's nothing inside m_ASCIIString.
I looked to make sure that it was being assigned some text in the first place, and that's not the problem. I also tried the signal/slot setup with and without const.
Any help would be appreciated.
Qt signal/slot mechanism needs metainformation about your custom types, to be able to send them in emitted signals.
To achieve that, register your type with qRegisterMetaType<MyDataType>("MyDataType");
Consult official QMetaType documentation for more information about this.
First, since you are using an auto connection, do both sender and receiver live in the same thread? If not, it could happen that the call is queued and when it arrives, the data in the sender was already modified. You could try to use a direct connection just to make sure this isn't the problem.
Second, just for the fun of it, did you try to access the sender by using qobject_cast<ControlIcon*>(sender()) within the slot? This is how it is usually done if the signal doesn't pass this as an argument. Like this:
QLabel *ASCIIStringHolder = new QLabel;
// this is instead of the argument to the slot:
ControlIcon *controlIcon = qobject_cast<ControlIcon*>(sender());
ASCIIStringHolder->setText(controlIcon->m_ASCIIString);
The signal can't be declared to be passing a class and then actually pass the child of that class. I changed the signal, slot, and connect() to be SerialController (the child of ControllerIcon), and everything worked fine.