How to get which QradioButton invoke the SLOT - c++

I create several QradioButton and connect to the same SLOT. In the slot, I want to know which QradioButton invoke the slot and do the related action. I found there is a way by using qobject_cast and QObject::sender(), but it seems not work. Here is the code:
header file:
class dialoginput : public QDialog
{
Q_OBJECT
public:
dialoginput(QWidget *parent = 0);
QRadioButton *radio1;
QRadioButton *radio2;
QRadioButton *radio3;
private slots:
void setText_2();
private:
QLabel *label_0_0;
QLabel *label_1;
};
main file:
dialoginput::dialoginput(QWidget *parent): QDialog(parent){
label_0_0 = new QLabel("label_1:");
label_1 = new QLabel;
QWidget *window = new QWidget;
QVBoxLayout *windowLayout = new QVBoxLayout;
QGroupBox *box = new QGroupBox("Display Type");
radio1 = new QRadioButton("3");
radio2 = new QRadioButton("5");
radio3 = new QRadioButton("9");
QVBoxLayout *radioLayout = new QVBoxLayout;
connect(radio1,SIGNAL(clicked()),this,SLOT(setText_2()));
connect(radio2,SIGNAL(clicked()),this,SLOT(setText_2()));
connect(radio3,SIGNAL(clicked()),this,SLOT(setText_2()));
radioLayout->addWidget(radio1);
radioLayout->addWidget(radio2);
radioLayout->addWidget(radio3);
box->setLayout(radioLayout);
windowLayout->addWidget(box);
windowLayout->addWidget(label_0_0);
windowLayout->addWidget(label_1);
window->setLayout(windowLayout);
window->show();
}
void dialoginput::setText_2(){
QObject *object = QObject::sender();
QRadioButton* pbtn = qobject_cast<QRadioButton*>(object);
QString name = pbtn->objectName();
label_1->setText(name);
if(!QString::compare(name, "3")){
}
else if(!QString::compare(name, "5")){
}
else if(!QString::compare(name, "9")){
}
}
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
dialoginput *input = new dialoginput();
return a.exec();
}

Even though using the sender() method solves your problem, i do not recommend using it. The problem is, signals and slots are designed to seperate the emitter and the receiver. A receiver does not need to know which objects, even what types of objects can trigger its slot. When you use sender(), you are relying on the fact that the receiver has knowledge of all of the objects that triggers its slot. What if this changes in the future?
You should take a look at QSignalMapper, it is designed specifically for this kind of needs. There are good examples about it in the docs.

You could create separate wrapper slots for each radio button, which then passes the information to the function you want to call. Something like this: -
class dialoginput : public QDialog
{
Q_OBJECT
public:
QRadioButton *radio1;
QRadioButton *radio2;
QRadioButton *radio3;
private slots:
void Radio1Selected() { setText_2(1); }
void Radio2Selected() { setText_2(2); }
void Radio3Selected() { setText_2(3); }
private:
void setText_2(int id);
};
Then connect each radio button: -
connect(radio1,SIGNAL(clicked()),this,SLOT(Radio1Selected()));
connect(radio2,SIGNAL(clicked()),this,SLOT(Radio2Selected()));
connect(radio3,SIGNAL(clicked()),this,SLOT(Radio3Selected()));
Now when setText_2 is called, the id will represent the selected radio button.

You are getting sender Object correctly on setText_2(), But you are not setting objectName property of radio1, radio2 and radio3. Please use "setObjectName( )" API.

write single argument custom signal for radiobuttons and then emit it .catch that argument in slot.check for corresponding radio button

You could also create a QButtonGroup and use lambda expression (c++11)
class dialoginput : public QDialog
{
Q_OBJECT
public:
private:
void setText_2(int id);
QRadioButton *radio1;
QRadioButton *radio2;
QRadioButton *radio3;
QButtonGroup _btnGroup;
};
After add the 3 QRadioButton to the QButtonGroup
_btnGroup.addButton(radio1, 1);
_btnGroup.addButton(radio2, 2);
_btnGroup.addButton(radio3, 3);
connect(&_btnGroup, static_cast<void(QButtonGroup::*)(int)>(&QButtonGroup::buttonClicked), [=](int id){
setText_2(id);});

Related

Access QT Widget child members from QT Widget Object Instance

Consider this QWidget initialized as:
QWidget *Logger;
Logger = new QWidget();
QPushButton *btn;
btn= new QPushButton(Logger);
btn->setObjectName(QStringLiteral("pushButton"));
Logger->show();
It display the Logger with a button with text pushButton.
Now Later if i want to access pushButton, i do it like this:
QPushButton *pushButton = Logger->findChild<QPushButton *>("pushButton");
pushButton->setText("NEW BUTTON");
I want to know is there a possibility to access directly this pushButton from Logger??Something like:
Logger->btn ...
I tried but it does not work. I have Widgets defined like this with many child objects and i wonder is this the only way to access them at run time??
EDIT: #drescherjm, So something along these lines you mean:
class MyWidget : QWidget
{
public:
QPushButton *pushButton;
MyWidget(){
pushButton = new QPushButton(this);
}
};
MyWidget *w = new MyWidget();
w->pushButton->setText("XYZ");
And is it worth it to create so many classes?? for small redundant tasks?
It won't work the way that you are expecting it to work. Use btn as long as it is in scope.
If you are creating btn somewhere locally, but your use-case demands you to use it in different places across your code, then you need to reconsider your design and make the QPushButton part of a class member.
Something of this sort :
#include <QPushButton>
class SampleWidget : public QWidget
{
public :
SampleWidget( QWidget * inParent );
// public methods to change the properties of the QPushButton go here.
void SetButtonText( QString const & inString );
bool IsButtonChecked();
private :
QPushButton *mSampleButton;
};
And in the implementation :
SampleWidget::SampleWidget(QWidget *parent)
:
mSampleButton( new QPushButton( parent ) )
{
// connect( mSampleButton,......... ); Connection to slot
}
void SampleWidget::SetButtonText( QString const & inString )
{
mSampleButton->setText( inString );
}
bool
SampleWidget::IsButtonChecked()
{
return mSampleButton->isChecked();
}
The question was not very clear on what you exactly want, but it seems like you are struggling to understand how to alter the attributes of a push button if it is a private member of a class and the above example will help you with that.

Switching between windows. Qt Widgets ( 1 widget in memory )

For example I have 2 widgets and I press button on first widget. I need to delete first widget and create new widget.
How is it possible? I mean some structure for this. I used stackedwidgets, but pages from stackedwidgets located in memory. I need to avoid this.
void Window::on_registrationButton_clicked(){
ui->logWindow->hide();
ui->RegistrWindow->show();
}
As you are going to eliminate the object you can not do it within the same class the object belongs to, you have to do it outside of it, for example in the following code I created a signal that is triggered when the button is pressed, this I have connected it to a lambda function where the new object is created and the object that emits it is eliminated.
class LogWindow: public QWidget{
Q_OBJECT
public:
LogWindow(const QString &text, QWidget *parent=Q_NULLPTR):QWidget(parent){
setLayout(new QVBoxLayout);
btn = new QPushButton(text, this);
layout()->addWidget(btn);
connect(btn, &QPushButton::clicked, this, &LogWindow::customSignal);
}
signals:
void customSignal();
private:
QPushButton *btn;
};
class RegWindow : public QWidget{
[...]
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
LogWindow *log= new LogWindow("LogWindow");
RegWindow *reg;
QObject::connect(log, &LogWindow::customSignal, [&reg, &log](){
reg = new RegWindow("RegWindow");
reg->show();
log->deleteLater();
});
log->show();
return a.exec();
}
#include "main.moc"
The complete example can be found in the following link

How to hide a temporary search bar?

I have a window that contains a browser. Up is a toolbar. In the bottom of the window is a search bar.
Search bar has a close button [x].
When the user clicks the close button I want the bar to disappear.
I want the bar only appear when user press CTRL + F. I tried to connect the close butoon with .hide() command, but application crashes. I need help.
.cpp
DocumentationWin::DocumentationWin (QWidget * parent){
docs = new QTextBrowser( this );
//Prepare toolbar
toolbar = new QToolBar( this );
//add stuff to toolbar
//Prepare footer bar
searchlabel = new QLabel(tr("Find in page:"),this);
resultslabel = new QLabel("",this);
searchinput = new QLineEdit();
findprev = new QToolButton(this);
findprev->setArrowType(Qt::UpArrow);
connect(findprev, SIGNAL(clicked()), this, SLOT (clickFindPrev()));
findnext = new QToolButton(this);
findnext->setArrowType(Qt::DownArrow);
connect(findnext, SIGNAL(clicked()), this, SLOT (clickFindNext()));
QStyle *style = qApp->style();
QIcon closeIcon = style->standardIcon(QStyle::SP_TitleBarCloseButton);
QPushButton *closeButton = new QPushButton(this);
closeButton->setIcon(closeIcon);
closeButton->setFlat(true);
connect(closeButton, SIGNAL(clicked()), this, SLOT (clickCloseFind()));
QWidget *bottom = new QWidget;
QHBoxLayout *footer = new QHBoxLayout();
casecheckbox = new QCheckBox(tr("Case sensitive"),this);
footer->setContentsMargins(5,5,5,5);
footer->addWidget(searchlabel);
footer->addSpacing(3);
footer->addWidget(searchinput);
footer->addWidget(findprev);
footer->addWidget(findnext);
footer->addSpacing(10);
footer->addWidget(casecheckbox);
footer->addSpacing(10);
footer->addWidget(resultslabel);
footer->addStretch(1);
footer->addWidget(closeButton);
bottom->setLayout(footer);
//Prepare main layout
layout = new QVBoxLayout;
layout->setContentsMargins(0,0,0,0);
layout->setSpacing(0);
layout->addWidget(toolbar);
layout->addWidget(docs);
layout->addWidget(bottom);
this->setLayout(layout);
this->show();
}
void DocumentationWin::clickCloseFind(){
bottom->hide();
}
.h
class DocumentationWin : public QDialog
{
Q_OBJECT
public:
DocumentationWin(QWidget * parent);
protected:
virtual void keyPressEvent(QKeyEvent *);
private slots:
void clickCloseFind();
private:
QVBoxLayout* layout;
QToolBar* toolbar;
QTextBrowser* docs;
QBoxLayout* footer;
QLabel *searchlabel;
QLabel *resultslabel;
QLineEdit *searchinput;
QToolButton *findprev;
QToolButton *findnext;
QCheckBox *casecheckbox;
QWidget *bottom;
QPushButton *closeButton;
};
Ahh, the classic case of local variables hiding the members. There have been quite a few identical questions on SO about this. This is wrong:
QWidget *bottom = new QWidget;
You want:
bottom = new QWidget;
You'll run into these problems always because you dynamically allocate all the widgets - that's completely unnecessary.
Suggestions:
Hold the child widgets and layouts by value, don't dynamically allocate them.
Don't pass a parent to widgets that are managed by a layout. Every widget that is laid out will be automatically parented.
Don't redundantly call setLayout. A QLayout takes the widget to lay its children on as a constructor argument.
QWidget::hide() is a slot.
Many widgets take the text as a constructor argument.
If you don't have any arguments to pass to the constructor in a new expression, you can drop the parentheses (but we try to avoid these anyway):
searchinput = new QLineEdit; // not QLineEdit();
Widgets shouldn't usually show() themselves upon construction. No Qt widget does that. It's up to the widget's user to do it.
C++ overloads a method call syntax with construction syntax. To differentiate the two, prefer uniform initialization (Type{arg0, arg1, ...}) over old syntax that used ().
Here's how your code can look when you're using C++11. This compiles with either Qt 4 or Qt 5. If you don't target Qt 4, you should be using the new connect syntax, though.
As you can see, there isn't a single explicit dynamic allocation - that's how quite a bit of C++11 code will look, when the used types are sane.
// https://github.com/KubaO/stackoverflown/tree/master/questions/find-hide-38082794
#include <QtGui>
#if QT_VERSION >= QT_VERSION_CHECK(5,0,0)
#include <QtWidgets>
#endif
class DocumentationWin : public QDialog
{
Q_OBJECT
public:
explicit DocumentationWin(QWidget * parent = 0);
private:
QVBoxLayout layout{this};
QToolBar toolbar;
QTextBrowser docs;
QWidget bottom;
QHBoxLayout footer{&bottom};
QLabel searchlabel{tr("Find in page:")};
QLabel resultslabel;
QLineEdit searchinput;
QToolButton findprev;
QToolButton findnext;
QCheckBox casecheckbox{tr("Case sensitive")};
QPushButton closeButton;
Q_SLOT void onFindPrev() {}
Q_SLOT void onFindNext() {}
};
DocumentationWin::DocumentationWin(QWidget * parent) : QDialog(parent) {
findprev.setArrowType(Qt::UpArrow);
connect(&findprev, SIGNAL(clicked()), this, SLOT(onFindPrev()));
findnext.setArrowType(Qt::DownArrow);
connect(&findnext, SIGNAL(clicked()), this, SLOT(onFindNext()));
auto style = qApp->style();
auto closeIcon = style->standardIcon(QStyle::SP_TitleBarCloseButton);
closeButton.setIcon(closeIcon);
closeButton.setFlat(true);
connect(&closeButton, SIGNAL(clicked(bool)), &bottom, SLOT(hide()));
footer.setContentsMargins(5,5,5,5);
footer.addWidget(&searchlabel);
footer.addSpacing(3);
footer.addWidget(&searchinput);
footer.addWidget(&findprev);
footer.addWidget(&findnext);
footer.addSpacing(10);
footer.addWidget(&casecheckbox);
footer.addSpacing(10);
footer.addWidget(&resultslabel);
footer.addStretch(1);
footer.addWidget(&closeButton);
layout.setContentsMargins(0,0,0,0);
layout.setSpacing(0);
layout.addWidget(&toolbar);
layout.addWidget(&docs);
layout.addWidget(&bottom);
}
int main(int argc, char ** argv) {
QApplication app{argc, argv};
DocumentationWin win;
win.show();
return app.exec();
}
#include "main.moc"

Qt QObject::connect() function cannot be connected

I have the code like this:
class MyListView : public QListView
{
public:
MyListView();
~MyListView();
public slots:
void insertData();
void deleteData();
void showData();
private:
QStringListModel *model;
QListView *listView;
};
And the constructor is like:
MyListView :: MyListView()
{
QStringList data;
data << "Letter A" << "Letter B" << "Letter C";
model = new QStringListModel;
model->setStringList(data);
listView = new QListView;
listView->setModel(model);
/* the three buttons */
QPushButton *insertBtn = new QPushButton(QObject::tr("insert"),this);
QObject::connect(insertBtn,SIGNAL(clicked()),this,SLOT(insertData()));
QPushButton *deleteBtn = new QPushButton(QObject::tr("delete"),this);
QObject::connect(deleteBtn,SIGNAL(clicked()),this,SLOT(deleteData()));
QPushButton *showBtn = new QPushButton(QObject::tr("show"),this);
QObject::connect(showBtn,SIGNAL(clicked()),this,SLOT(showData()));
/* layout */
QHBoxLayout *btnLayout = new QHBoxLayout;
btnLayout->addWidget(insertBtn);
btnLayout->addWidget(deleteBtn);
btnLayout->addWidget(showBtn);
QVBoxLayout *mainLayout = new QVBoxLayout(this);
mainLayout->addWidget(listView);
mainLayout->addLayout(btnLayout);
setLayout(mainLayout);
}
So I want to connect the push button to the slot functions, but when I compile it, I got the error message as:
QObject::connect: No such slot QListView::insertData()
I think the problem comes from the connect function, in which, "this" is not the right pointer, any help? Thanks in advance.
You need to add the Q_OBJECT macro in your MyListView
From Qt API docs:
Notice that the Q_OBJECT macro is mandatory for any object that
implements signals, slots or properties. You also need to run the Meta
Object Compiler on the source file. We strongly recommend the use of
this macro in all subclasses of QObject regardless of whether or not
they actually use signals, slots and properties, since failure to do
so may lead certain functions to exhibit strange behavior.
So, it should be:
class MyListView : public QListView
{
Q_OBJECT
public:
...
}

In Qt how do I get a button press to set a spinbox to a certain value?

I'm trying to get to grips with Qt's signal and slots mechanism. I have an app with a QPushButton and a QSpinBox. When I click the button I want the spinbox to change to 20. What signal and slot do I need to set up?
The code below shows the app, the connect function is the one I am having trouble with.
As I understand it the setValue(int) slot of QSpinBox will not work here because the clicked() signal of QPushButton has a different signature, and anyway how would I pass the value 20 to the spinbox? Do I need to write some sort of auxiliary function to act as a slot which calls spinbox->setValue(20)? If so, what form would that take?
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QWidget *window = new QWidget;
QSpinBox *spinbox = new QSpinBox;
QPushButton *button = new QPushButton("Set to 20");
spinbox->setRange(0, 100);
// What should I put below?
QObject::connect(button, SIGNAL(clicked()), spinbox, SLOT(???????));
QLayout *layout = new QHBoxLayout;
layout->addWidget(spinbox);
layout->addWidget(button);
window->setLayout(layout);
window->show();
return app.exec();
}
You can either do:
class AuxSignals : public QObject
{
Q_OBJECT
...
signals:
void valueChanged(int);
public slots:
void buttonClicked() { emit valueChanged(20); }
};
...
// On main.cpp
AuxSignals *auxSignals = new AuxSignals;
QObject::connect(button, SIGNAL(clicked()), auxSignal, SLOT(buttonClicked));
QObject::connect(auxSignals, SIGNAL(valueChanged(int)), spinbox, SLOT(setValue(int)));
or
class AuxSignals : public QObject
{
Q_OBJECT
...
QSpinBox *m_spinBox;
public:
AuxSignals(QSpinBox *spinBox) : m_spinBox(spinBox) {}
public slots:
void buttonClicked() { m_spinBox->setValue(20); }
};
...
// On main.cpp
AuxSignals *auxSignals = new AuxSignals(spinBox);
QObject::connect(button, SIGNAL(clicked()), auxSignals, SLOT(buttonClicked()));
I prefer the first option because it doesn't require the AuxSignals class to have a pointer to a specific QWidget.
I think you are looking at a custom SLOT here. A QPushButton::clicked signal will give a boolean (true|false) event. If you catch it using QSpinBox::setValue you won't go very far. The QSpinBox::setValue expects an int and converts the input boolean to 0 or 1 as the case maybe and your spinbox increments by only 1 unit. If you were to write a custom SLOT you can actually set the exact slider value with far more control.