I want to write a simple QtCreator program with the help of QtCreator in C++ created an event that, when I clicked a button, should give it a true property. This is my first experience with С++ and Qt , please explain in detail what and how, I do not correctly and why this code does not work, because I choose an object and then try to assign it true

There is such code:

 void MainWindow::on_poweButton_clicked() { QCheckBox powerCheck; powerCheck::setChecked(true); } 
  • And the question is what? - Vladimir Martyanov
  • @nick_n_a in the GUI they are already laid. - Insider
  • QCheckBox is a button, and where is it located? Maybe it should be linked to a form, somehow by ah-di or by name? It looks like it is declared just as a local variable. - nick_n_a
  • @nick_n_a prntscr.com/cibwhb looks like this in the GUI. This is my first experience with C ++, I don’t know how to connect them and that QCheckBox is your button. - Insider
  • The first experience in C ++ immediately decided to get from GUI to Qt? - αλεχολυτ

2 answers 2

Your code creates a temporary button and makes it pressed. The button is not added to the form and is deleted after exiting the function.

 void MainWindow::on_poweButton_clicked() { QPushButton*powerCheck=dynamic_cast<QPushButton*>(QObject::sender()); powerCheck->setChecked(true); } 

When creating a button, add setCheckable (true)

  • I get the error Cannot convert 'QPushButton * to CheckBox *' in initialization QCheckBox * powerCheck = dynamic_cast <QPushButton *> (QObject :: sender ()); - Insider
  • Malyas typo QPushButton * powerCheck - Evgeny Shmidt

Suppose you wanted to do something like this:

 #ifndef WINDOW_H #define WINDOW_H #include <QWidget> #include <QVBoxLayout> #include <QPushButton> #include <QCheckBox> class Window : public QWidget{ Q_OBJECT QCheckBox *_checkBox; QPushButton *_pushButton; public: Window(QWidget *parent = 0): QWidget(parent), _checkBox(new QCheckBox("Чек бокс")), _pushButton(new QPushButton("Кнопка")) { QVBoxLayout *layout = new QVBoxLayout(this); layout->addWidget(_checkBox); layout->addWidget(_pushButton); connect(_pushButton, SIGNAL(clicked(bool)), this, SLOT(_setCheckBoxChecked())); } private slots: void _setCheckBoxChecked(){ _checkBox->setChecked(true); } }; #endif // WINDOW_H 

I strongly recommend that you first learn C ++, before learning Qt, it will save you a lot of time.