Remove Labels in qt

2.4k views Asked by At

I want to remove a label in Qt when program is running but i do not want to delete it.I want to remove it for several seconds and then show it. How can i do this?

Sample code:

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

#include "QTimer"
#include "QTime"
#include "QMessageBox"

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

    movePicture();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::movePicture()
{
    QTimer *timer = new QTimer(this);
    timer->setInterval(1000);
    timer->start();
    connect(timer,SIGNAL(timeout()),SLOT(updateloc()));
}

int MainWindow::addx()
{
    QPoint P = ui->label->pos();
    int x = P.x() + 15;
    return x;
}

int MainWindow::decreasexEnemy()
{
    QPoint P = ui->Enemy->pos();
    int x = P.x() - 15;
    return x;
}

void MainWindow::updateloc()
{
    QString timestring = QTime::currentTime().toString("hh:mm:ss");
    ui->lbltime->setText(timestring);

    int xEnemy = ui->Enemy->pos().x();
    int x = ui->label->pos().x();

    if((xEnemy - x) >150 )
    {
        x = addx();
        xEnemy = decreasexEnemy();
        ui->Enemy->move(xEnemy,70);
        ui->label->move(x,70);
    }
    else
    {
    }
}

In else i want to remove label.

1

There are 1 answers

0
TheDarkKnight On BEST ANSWER

Assuming you're using C++11, to remove for a few seconds, you can hide the label, then show it again with the use of a timer and a lambda function:

// hide the label
ui->label->hide();

// create a timer to show the label in 5 seconds
QTimer* pShowTimer = new QTimer;
pShowTimer->setSingleShot(true);

connect(pShowTimer, &QTimer::timeout, [=](){

    // show the label and tidyup the timer
    ui->label->show();
    pShowTimer->deleteLater();
});

pShowTimer->start(1000 * 5); // 5 seconds