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 label.show(), it works. Here is the code.

    void MainWindow::on_actionRefresh_triggered()
    {

    QLabel label ("Refreshing");
    label.show();
    

    }

    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
    {
    Q_OBJECT

    public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

    private:
    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) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
    {
    ui->setupUi(this);
    mLabel=new QLabel(this);
    mLabel->setText("Refreshing");
    mLabel->hide();
    }

    MainWindow::~MainWindow()
    {
    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
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.