c++ - 从QT的MainWindow中的另一个函数更新标签

标签 c++ qt user-interface

我是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)。我想在currentDateTime的每1秒刻度上更新一次带有时间的标签(timer)。我将计时器信号连接到一个插槽(myFunc)。在myFunc中,我想访问标签以在正确的时间更新文本,但这给了我错误。
我想知道两件事
  • 在这种MainWindow类的自动创建中,如何声明privatepublic数据以及成员函数
  • 如何从currentDateTime访问此myFunc()标签。

  • 帮助将不胜感激。

    最佳答案

    In this auto-creation of MainWindow class how can I declare private and public data and member functions,


    您可以在mainwindow.h文件中做到这一点。
    class MainWindow {
    public:
    //...
    private:
    //...
    }
    

    How can I access this currentDateTime label from myFunc().


    您无法访问它,因为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++ - 从QT的MainWindow中的另一个函数更新标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62508803/

    相关文章:

    C++相当于Python的日志库

    c++ - 优化非成本变量访问

    c++ - 从 QLabel 获取 QPixmap

    Java Swing FlowLayout 对齐

    Android progress Dialog 只更新 Message ,不更新 bar 和 lines

    java - 富客户端 UI 的设计建议

    c++ - 常量成员函数如何以这种形式工作?

    c++ - 我怎样才能把这个qt程序放到一个源代码文件中

    qt - 通过 MouseArea 向 ChartView 添加橡皮筋缩放

    c++ - 获取崩溃的堆栈跟踪,无需在调试器中运行应用程序