文本可以使用QTimer和QLabel的setText()函数结合实现。
首先需要创建一个QLabel对象,并将其添加到窗口中。
然后在初始化函数中设置一个计时器,每隔一定时间更新QLabel的文本内容。
在计时器的槽函数中更新QLabel的文本内容,可以使用QString::number()函数将数字转换为字符串类型。
示例代码:
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QLabel>
#include <QTimer>
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private:
QLabel *label;
QTimer *timer;
int count;
private slots:
void updateLabel();
};
#endif // MAINWINDOW_H
mainwindow.cpp
#include "mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
label = new QLabel(this);
label->setGeometry(10, 10, 100, 20);
timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(updateLabel()));
timer->start(1000); // 设置计时器间隔为1s
count = 0; // 初始化计数器为0
}
MainWindow::~MainWindow()
{
}
void MainWindow::updateLabel()
{
count++; // 每次计数器加1
QString text = "Count: " + QString::number(count); // 将数字转换为字符串并拼接成文本
label->setText(text); // 更新QLabel的文本内容
}
运行程序后,QLabel的文本内容会每隔1秒更新一次,显示当前的计数器值。