I've set a placeholder in a QLabel
to "user".
After ui->setupUi(this);
, QLabel
gets changed via ui->label->setText("superuser");
. No changes are made afterwards.
As soon as QMainWindow
is initialized and shown via mw.show();
in main.cpp
file , QLabel
is set to the placeholder "user" again.
I tried:
qDebug()<<ui->label->text();
before and afterui->label->setText("superuser");
and placed one right at the end of constructor ofQMainWindow
. Results:user superuser superuser
- Checked
mainwindow.ui
in nano, all is right. - Checked connections: there are no connections that are linked to the function that changes
QLabel
. - Checked if
mw->show();
is triggered multiple times inmain.cpp
, one call. - No external thread changes the
QLabel
outside fromQMainWindow
.
Here's a minimal reproducible example:
mainwindow.cpp
:
#include "mainwindow.h"
#include "ui_mainwindow.h"
using namespace std;
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
this->init();
qDebug() << "afterInit" << ui->label->text();
}
void MainWindow::init()
{
this->set_options("SuperUser");
}
void MainWindow::set_options(QString s)
{
debugInt++;
qDebug() << debugInt;
qDebug() << ui->label->text();
ui->label->setText(s);
qDebug() << ui->label->text();
}
void MainWindow::on_actionLogout_triggered()
{
this->set_options("User");
}
mainwindow.h
:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QtWidgets/QMainWindow>
#include <QDebug>
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public slots:
void set_options(QString s);
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private:
void init();
Ui::MainWindow *ui;
int debugInt=0;
private slots:
void on_actionLogout_triggered();
};
#endif //MAINWINDOW_H
main.cpp
:
#include "mainwindow.h"
#include <QtWidgets/QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
a.setQuitOnLastWindowClosed(true);
MainWindow w;
w.show();
return a.exec();
}
ui->label
is set to "Current: user" in mainwindow.ui
. That's the standard set text that I call placeholder.
mainwindow.ui
:
<property name="text">
<string>Current: user</string>
My QDebug
output when I start the program and then press logout:
1
"Current: user"
"Current: SuperUser"
"afterInit "Current: SuperUser"
2
"Current: user"
"Current: User"
As you can see, by default ui->label
is set to "Current: user". In the init
process it gets overwritten to "Current: SuperUser". But when I start the program, it is shown as "Current: user". As soon as I click the actionLogout
(menubarbutton
in mainwindow_ui
), ui->label
is set to "Current: User" and gets shown right.
Note: I created a new program with the given code. Works as it should, ui->label
isn't changed in any other function in my code.