Home > Net >  What am I doing wrong trying to change QPushButton text at runtime?
What am I doing wrong trying to change QPushButton text at runtime?

Time:01-22

I'm new to coding with QTCreator, and Linux Graphical Development in general. What is the, probably trivial, thing I am doing wrong here?

I could write this code and make it work easily without using the form method, but I'd really prefer to use the graphical interface, as it should be faster (once I know what compiler wants me to do).

When I enter this code it tells me that btnStopGo isn't defined in this context. I used the forms interface to drop the button onto a form.

The code is in the file mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

...

void MainWindow::on_btnStopGo_clicked()
{
    if (bDoStream){
        if (bStreaming){
            //TODO: Send stop stream signal, save stream to file, dispose stream
            bStreaming = false;
            btnStopGo->setText("Go");
        }
        else{
            btnStopGo->setText("Stop");
            bStreaming = true;
            // TODO: request a stream of quotes
        }
    }
    else {
        // TODO: Get a single quote tick
    }

}

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
    Q_OBJECT;

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();
    ...

private slots:
    ...

    void on_btnSelect_clicked();

    void on_btnStopGo_clicked();

private:
    Ui::MainWindow *ui;

};
#endif // MAINWINDOW_H

Other visible files in the project are : Hello2.pro, main.cpp, and mainwindow.ui. main.cpp declares mywindow as the variable to access the main window. I've tried using "ui.btnStopGo", mywindow.btnStopGo, ui->btnStopGo (blows up the compiler), and every other combo I can think of. None of them work so far.

I don't know if this is relevant but I'm using: Qt Creator 4.11.0 Based on Qt 5.12.8 (GCC 9.3.0, 64 bit) on a Linux Mint 20 Cinnamon with KDE added manually.

CodePudding user response:

If you put the button in the form designer, and called the button btnStopGo, then it ends up compiled into the ui_mainwindow.h and .cc files. Your MainWindow class, which you wrote yourself, doesn't have a (member) variable called btnStopGo. It does have a variable ui, which points to the user interface which was generated from the form designer.

Use ui->btnStopGo->setText("stop") instead.

  •  Tags:  
  • Related