使用Signal和Slot QT更新QLineEdit

时间:2014-03-25 15:13:39

标签: c++ qt qlineedit

我正在写信,询问有关如何使用QT库最好地实现我的代码的建议。我有一个名为Action类的类,每隔一秒检索一次PC时间(使用gettimeofday),该值将显示在GUI中。所以我有一个类小部件,它定义了GUI所需的所有小部件。使用QLineEdit显示值(以秒表示)。 所以我的问题是,我如何实现Signal和slot来更新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();
}

1 个答案:

答案 0 :(得分:4)

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

使用线程在这里完全过时了。