我是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
类的自动创建中,如何声明private
和public
数据以及成员函数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/