用信号和槽QT更新QLineEdit

Update QLineEdit with Signal and Slot QT

本文关键字:更新 QLineEdit QT 信号      更新时间:2023-10-16

我写信是为了征求关于如何最好地使用QT库实现我的代码的建议。我有一个类叫Action类,它每秒钟检索一次PC时间(使用gettimeofday),这个值将显示在GUI中。因此,我有一个类小部件,它定义了GUI所需的所有小部件。该值(以秒为单位)将与QLineEdit一起显示。所以我的问题是,我如何实现信号和插槽来更新QLineEdit中的值?我应该发出一个信号,每次函数retreiveTimetoSend被调用?

action.h

class Action: public object
{
    Q_OBJECT
private:
    Qtimer timer;
    unisgned int timetosend;
private:
    void retreiveTimetoSend();
public:
    Action();
    ~Action();
public slots:
    void doWork();
}

action.cpp

void retreiveTimetoSend()
{
    struct timeval Now;
    unsigned int Sec;
    gettimeofday(&Now, NULL);
    Sec = Now.tv_sec;
    time.value =Sec; 
}
void Action::Action()
{
    timer.setInterval(1000);
    connect(&timer, SIGNAL(timeout()), this, SLOT (doWork()));
    timer.start();
}
void Action::doWork()
{
    retreiveTimetoSend()
}

widget.h

class widgets: public QWidget
{
    Q_OBJECT
private:
    QLineEdit *displayTime;
public:
    widget(action *w_test);
}

widget.cpp

widgets::widgets(action *w_test)
{
    displayTime= new QLineEdit();
    displayTime->setText(QString::number(w_test->timetosend,10));
    displayTC->setStyleSheet("color: blue; background-color: red");
}

main.cpp

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    Action *test = new Action;
    Thread *threadtest  = new QThread;
    test->moveToThread(threadtest);
    QObject::connect(threadtest, SIGNAL(started()), test ,SLOT(doWork()));
    widget *mainwindows = new widget(test);
    mywindow->show();
    threadtest->start();
    return app.exec();
}

使用gettimeofday使用QTime::currentTime然后将其转换为字符串(选择格式)并发出结果。此信号应连接到插槽QLineEdit::setText。

在这里使用thread是完全过时的