How do I create a pause/wait function using Qt?

后端 未结 12 2199
执笔经年
执笔经年 2020-11-27 15:19

I\'m playing around with Qt, and I want to create a simple pause between two commands. However it won\'t seem to let me use Sleep(int mili);, and I can\'t find

12条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-27 16:24

    Since you're trying to "test some class code," I'd really recommend learning to use QTestLib. It provides a QTest namespace and a QtTest module that contain a number of useful functions and objects, including QSignalSpy that you can use to verify that certain signals are emitted.

    Since you will eventually be integrating with a full GUI, using QTestLib and testing without sleeping or waiting will give you a more accurate test -- one that better represents the true usage patterns. But, should you choose not to go that route, you could use QTestLib::qSleep to do what you've requested.

    Since you just need a pause between starting your pump and shutting it down, you could easily use a single shot timer:

    class PumpTest: public QObject {
        Q_OBJECT
        Pump &pump;
    public:
        PumpTest(Pump &pump):pump(pump) {};
    public slots:
        void start() { pump.startpump(); }
        void stop() { pump.stoppump(); }
        void stopAndShutdown() {
            stop();
            QCoreApplication::exit(0);
        }
        void test() {
            start();
            QTimer::singleShot(1000, this, SLOT(stopAndShutdown));
        }
    };
    
    int main(int argc, char* argv[]) {
        QCoreApplication app(argc, argv);
        Pump p;
        PumpTest t(p);
        t.test();
        return app.exec();
    }
    

    But qSleep() would definitely be easier if all you're interested in is verifying a couple of things on the command line.

    EDIT: Based on the comment, here's the required usage patterns.

    First, you need to edit your .pro file to include qtestlib:

    CONFIG += qtestlib
    

    Second, you need to include the necessary files:

    • For the QTest namespace (which includes qSleep): #include
    • For all the items in the QtTest module: #include . This is functionally equivalent to adding an include for each item that exists within the namespace.

提交回复
热议问题