Solved casting sender() to wanted type returns nullptr
-
in my event handling function i have such code:
void Widget::mousePressEvent(QMouseEvent *event) { const auto button = event->button(); if (button == Qt::LeftButton) { emit leftClicked(getName()); } ... } QString Widget::getName() const { // return some string }
then, somewhere else i connect the signal to a slot, where i use the passed string.
now, if i write the above code asvoid Widget::mousePressEvent(QMouseEvent *event) { const auto button = event->button(); if (button == Qt::LeftButton) { emit leftClicked(); // <---- not passing the argument } ... }
and in the connected slot do this
void OtherWidget::onLeftClicked() { if (auto widget = qobject_cast<Widget *>(sender())) // <--- widget == nullptr // use widget->getName() analogously }
what's wring here?
-
Hi
The type of sender() cannot be altered by omitting a parameter.
Something else must be going on.Do you connect onLeftClicked to any other object than a Widget? ( bad name btw :)
-
the actual name is different
and absolutely no, this is what i do
auto pWidget = new Widget; connect(pWidget, &Widget::leftClicked, [this] { onLeftClicked(); });
-
@user4592357
Ah, its a lambda.
please see
https://forum.qt.io/topic/30568/how-to-get-the-sender-in-a-c-lambda-signal-slot-handler/5Basically you have to capture the sender manually.
-
@mrjj
oh thanks!
i'm on mobile so can't try to run the code.
if i capture the sender, and call the slot from within lambda, and then get sender in that slot, will that be okay? or i need to use the sender object directly in lambda body? -
@user4592357
You use the captured sender directly in the lambda.