我如何检查2 keypressevent之间的时间戳差异

时间:2018-04-13 06:38:23

标签: qt timestamp focus

当2个键之间的时差大于100毫秒时,我正在尝试在两次编辑之间更改焦点。如果每次输入一个键都有keyPressed(..)功能,我怎么能记住最后一个键输入?

1 个答案:

答案 0 :(得分:1)

我不会使用QTime,因为它取决于系统时钟。我会使用QElapsedTimerQTimer

QTimer的示例:

#include <QtWidgets>

class Widget : public QWidget
{
    Q_OBJECT
public:
    Widget(QWidget *parent = nullptr) : QWidget(parent)
    {
        setLayout(new QHBoxLayout);
        layout()->addWidget(&line_edit1);
        layout()->addWidget(&line_edit2);
        focus_timer.setInterval(100);
        focus_timer.setSingleShot(true);
        connect(&line_edit1, &QLineEdit::textEdited, &focus_timer, QOverload<>::of(&QTimer::start));
        connect(&line_edit2, &QLineEdit::textEdited, &focus_timer, QOverload<>::of(&QTimer::start));
        connect(&focus_timer, &QTimer::timeout, this, [&]
        {
            line_edit1.hasFocus() ? line_edit2.setFocus() : line_edit1.setFocus();
        });
    }
private:
    QLineEdit line_edit1;
    QLineEdit line_edit2;
    QTimer focus_timer;
};

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Widget w;
    w.show();
    return a.exec();
}

#include "main.moc"