Important: Please read the Qt Code of Conduct -

QLabel local variable not showing up

  • Hi,

    I am new to QT and was experimenting few stuffs to get going. I created a UI layout and added menu Tool bar.
    Upon clicking one of the menu option i invoke _triggered function. Inside that i am creating local variable of QLabel and displaying some message., However this does not show up!. If i creating a member in my class and invoke, it works. Here is the code.

    void MainWindow::on_actionRefresh_triggered()

    QLabel label ("Refreshing");;


    Is there anything that i am doing wrong?

  • Hi
    Welcome to Qt!
    Your local variable (label) is going out of scope.
    You could create it as a pointer -

    QLabel* label = new QLabel("Refreshing");

    Also when including code in your posts you should use code blocks

    Hope this helps

  • Hi and welcome to devnet:

    change your mainwindow to this:

    #ifndef MAINWINDOW_H
    #define MAINWINDOW_H

    #include <QMainWindow>
    #include <QLabel>

    namespace Ui {
    class MainWindow;

    class MainWindow : public QMainWindow

    explicit MainWindow(QWidget *parent = 0);

    Ui::MainWindow *ui;
    QLabel *mLabel;

    #endif // MAINWINDOW_H


    instantiate the label in the constructor like this(mainwindow.cpp)

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

    MainWindow::MainWindow(QWidget *parent) :
    ui(new Ui::MainWindow)
    mLabel=new QLabel(this);

    delete ui;


    and in your slot you can do what you did showing the label.Also it is good practice to wrap your code inside @s for readability.

  • Hmm,
    But your code does work fine. What it does is:

    • Create a QLabel (probably a floating window since it doesn't have a parent)
    • Set the text of the QLabel
    • Show the QLabel on screen
    • Delete the QLabel (function closed!!!!!, scope lost)
      The Show function is only to get the widget on top and not minimized etc, but you delete it immediately when the function is completed, so it gets removed from screen.
      Just some thoughts:
      Add a Qlabel to your statusBar (comes with MainWindow-form) and place the information there or generate a QMessagebox::information() in your triggered slot. that is a modal dialog that needs to be accepted/cleared before being removed from screen.

Log in to reply