【问题标题】:Updating label from another function in MainWindow in QT从 QT 的 MainWindow 中的另一个函数更新标签
【发布时间】:2020-06-22 06:44:50
【问题描述】:

我是 QT 的新手。我通过向导创建了一个应用程序。它的 UI 后端创建如下。

QTimer *timer; // NEW
void TimerSlot(); // NEW slot
MainWindow::MainWindow(QWidget *parent) 
    : QMainWindow(parent)

    , ui(new Ui::MainWindow)
{
    //saveSetting();
    loadSettings();
    ui->setupUi(this);
//    this->layout()->setSizeConstraint(QLayout::SetFixedSize);
    const QString time = QDateTime::currentDateTime().toString();
    ui->currentDateTime->clear();
    ui->currentDateTime->setText(time);
    timer = new QTimer(this); // create it
    connect(timer, &QTimer::timeout, this, TimerSlot); // connect it
    timer->start(1000); // 1 sec timer
}

void TimerSlot()
{

   ui->lbl.setText(QDateTime::currentDateTime().toString());
}

我在 UI 上放置了一个名为 currentDateTime 的标签。我创建了一个计时器和一个名为 myFunc() 的函数来更新标签上的时间 (lbl)。我想在timer 的每 1 秒滴答声中更新标签 (currentDateTime)。我将定时器信号与插槽 (myFunc) 连接起来。在myFunc 中,我想访问标签以使用正确的时间更新文本,但它给了我错误。

我想知道两件事,

  1. MainWindow 类的自动创建中,我如何声明privatepublic 数据和成员函数,
  2. 如何从myFunc() 访问此currentDateTime 标签。

我们将不胜感激。

【问题讨论】:

    标签: c++ qt user-interface


    【解决方案1】:

    在这个 MainWindow 类的自动创建中,我如何声明私有和公共数据以及成员函数,

    您可以在 mainwindow.h 文件中执行此操作。

    class MainWindow {
    public:
    //...
    private:
    //...
    }
    

    如何从 myFunc() 访问这个 currentDateTime 标签。

    您无法访问它,因为TimerSlot 函数不是MainWindow 类的成员函数。因此您无法访问变量ui

    要解决此问题,请将 TimerSlot() 函数移到 MainWindow 类中:

    class MainWindow {
    //...
    private slots:
      void TimerSlot();
    };
    

    然后在mainwindow.cpp文件中定义:

    void MainWindow::TimerSlot()
    {
      ui->lbl.setText(QDateTime::currentDateTime().toString());
    }
    

    此外,不建议无故创建全局对象。我建议你将 QTimer *timer; // NEW 移到 MainWindow 类中:

    class MainWindow {
    //...
    private:
      QTimer *timer; // NEW
    }
    

    【讨论】:

    • 感谢亲爱的回复和帮助。实际上在很长一段时间后重新使用 C++(尤其是在 python 和 matlab 中工作)会让人犯一些愚蠢的错误。它工作得很好。再次感谢兄弟的帮助。我对你的帖子投了赞成票,但我是新用户,没有声誉,它刚刚记录下来,没有公开更新。
    • 接受并感谢 :) 你能通过支持问题帮助我获得声誉吗?
    • 我不认为 SO 只关乎声誉,而是学习和教学。也许考虑阅读这个:meta.stackoverflow.com/questions/323847/…
    猜你喜欢
    • 1970-01-01
    • 2021-08-10
    • 2017-08-10
    • 2021-03-26
    • 1970-01-01
    • 1970-01-01
    • 2016-10-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多