Qt를 사용하여 일시 중지 / 대기 기능을 어떻게 생성합니까?
Qt를 가지고 놀고 있는데 두 명령 사이에 간단한 일시 중지를 만들고 싶습니다. 그러나 그것은 내가 사용할 수있게하지 않는 것 같고 Sleep(int mili);
명백한 대기 기능을 찾을 수 없습니다.
기본적으로 콘솔 응용 프로그램을 만들어 나중에 적절한 Qt GUI에 포함될 일부 클래스 코드를 테스트하고 있으므로 지금은 전체 이벤트 기반 모델을 깨는 것에 대해 신경 쓰지 않습니다.
이 이전 질문qSleep()
은 QtTest
모듈 에있는 사용 에 대해 언급 합니다. QtTest
모듈 에서 오버 헤드 링크를 피하려면 해당 함수의 소스를 살펴보고 자신 만의 복사본을 만들어 호출 할 수 있습니다. 정의를 사용하여 Windows Sleep()
또는 Linux 를 호출합니다 nanosleep()
.
#ifdef Q_OS_WIN
#include <windows.h> // for Sleep
#endif
void QTest::qSleep(int ms)
{
QTEST_ASSERT(ms > 0);
#ifdef Q_OS_WIN
Sleep(uint(ms));
#else
struct timespec ts = { ms / 1000, (ms % 1000) * 1000 * 1000 };
nanosleep(&ts, NULL);
#endif
}
Qt에서 개발 한 응용 프로그램에 대해 매우 간단한 지연 함수를 작성했습니다.
GUI가 멈추지 않도록 절전 기능보다이 코드를 사용하는 것이 좋습니다.
다음은 코드입니다.
void delay()
{
QTime dieTime= QTime::currentTime().addSecs(1);
while (QTime::currentTime() < dieTime)
QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
}
이벤트를 n 초 지연 시키려면을 사용하십시오 addSecs(n)
.
Qt5부터는
void msleep(unsigned long msecs)
void sleep(unsigned long secs)
void usleep(unsigned long usecs)
kshark27 의 대답에 대한 작은 +1은 동적으로 만듭니다.
#include <QTime>
void delay( int millisecondsToWait )
{
QTime dieTime = QTime::currentTime().addMSecs( millisecondsToWait );
while( QTime::currentTime() < dieTime )
{
QCoreApplication::processEvents( QEventLoop::AllEvents, 100 );
}
}
우리는 아래 클래스를 사용하고 있습니다-
class SleepSimulator{
QMutex localMutex;
QWaitCondition sleepSimulator;
public:
SleepSimulator::SleepSimulator()
{
localMutex.lock();
}
void sleep(unsigned long sleepMS)
{
sleepSimulator.wait(&localMutex, sleepMS);
}
void CancelSleep()
{
sleepSimulator.wakeAll();
}
};
QWaitCondition은 서로 다른 스레드간에 대기중인 뮤텍스를 조정하도록 설계되었습니다. 그러나 이것이 작동하는 이유는 wait 메소드에 시간 초과가 있다는 것입니다. 이런 식으로 호출하면 절전 기능과 똑같이 작동하지만 타이밍을 위해 Qt의 이벤트 루프를 사용합니다. 따라서 일반 Windows 절전 기능처럼 다른 이벤트 또는 UI가 차단되지 않습니다.
보너스로 CancelSleep 기능을 추가하여 프로그램의 다른 부분에서 "sleep"기능을 취소 할 수 있습니다.
이것에 대해 우리가 좋아하는 것은 가볍고 재사용이 가능하며 완전히 독립적이라는 것입니다.
QMutex : http://doc.qt.io/archives/4.6/qmutex.html
QWaitCondition : http://doc.qt.io/archives/4.6/qwaitcondition.html
"일부 클래스 코드를 테스트"하려고하므로 QTestLib 사용 방법을 배우는 것이 좋습니다 . 그것은 제공 QTEST 공간 및 QtTest 모듈 을 포함한 유용한 기능 및 개체의 숫자 포함 QSignalSpy 특정 신호가 방출되는 것을 확인하는 데 사용할 수있다.
결국 전체 GUI와 통합하게되므로 QTestLib를 사용하고 잠자기 또는 대기없이 테스트하면 실제 사용 패턴을 더 잘 나타내는보다 정확한 테스트를 얻을 수 있습니다. 그러나 해당 경로를 사용 하지 않기로 선택 하면 QTestLib :: qSleep 을 사용 하여 요청한 작업을 수행 할 수 있습니다.
펌프를 시작하고 종료하는 사이에 잠시 멈추기 만하면되기 때문에 단일 샷 타이머를 쉽게 사용할 수 있습니다.
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();
}
하지만 qSleep()
관심있는 모든 것이 명령 줄에서 몇 가지 사항을 확인하는 것이라면 확실히 더 쉬울 것입니다.
편집 : 의견에 따라 필요한 사용 패턴은 다음과 같습니다.
먼저 qtestlib를 포함하도록 .pro 파일을 편집해야합니다.
CONFIG += qtestlib
둘째, 필요한 파일을 포함해야합니다.
- For the QTest namespace (which includes
qSleep
):#include <QTest>
- For all the items in the
QtTest
module:#include <QtTest>
. This is functionally equivalent to adding an include for each item that exists within the namespace.
To use the standard sleep function add the following in your .cpp file:
#include <unistd.h>
As of Qt version 4.8, the following sleep functions are available:
void QThread::msleep(unsigned long msecs)
void QThread::sleep(unsigned long secs)
void QThread::usleep(unsigned long usecs)
To use them, simply add the following in your .cpp file:
#include <QThread>
Reference: QThread (via Qt documentation): http://doc.qt.io/qt-4.8/qthread.html
Otherwise, perform these steps...
Modify the project file as follows:
CONFIG += qtestlib
Note that in newer versions of Qt you will get the following error:
Project WARNING: CONFIG+=qtestlib is deprecated. Use QT+=testlib instead.
... so, instead modify the project file as follows:
QT += testlib
Then, in your .cpp file, be sure to add the following:
#include <QtTest>
And then use one of the sleep functions like so:
usleep(100);
I've had a lot of trouble over the years trying to get QApplication::processEvents to work, as is used in some of the top answers. IIRC, if multiple locations end up calling it, it can end up causing some signals to not get processed (https://doc.qt.io/archives/qq/qq27-responsive-guis.html). My usual preferred option is to utilize a QEventLoop (https://doc.qt.io/archives/qq/qq27-responsive-guis.html#waitinginalocaleventloop).
inline void delay(int millisecondsWait)
{
QEventLoop loop;
QTimer t;
t.connect(&t, &QTimer::timeout, &loop, &QEventLoop::quit);
t.start(millisecondsWait);
loop.exec();
}
Similar to some answers here, but maybe a little more lightweight
void MyClass::sleepFor(qint64 milliseconds){
qint64 timeToExitFunction = QDateTime::currentMSecsSinceEpoch()+milliseconds;
while(timeToExitFunction>QDateTime::currentMSecsSinceEpoch()){
QApplication::processEvents(QEventLoop::AllEvents, 100);
}
}
If you want a cross-platform method of doing this, the general pattern is to derive from QThread and create a function (static, if you'd like) in your derived class that will call one of the sleep functions in QThread.
@kshark27's answer didn't work for me for some reason (because I use Qt 5.7?) so I ended up doing this:
while (someCondition) {
// do something
QApplication::processEvents();
QThread::sleep(1); // 1 second
};
If this is done in the GUI thread, it obviously introduces a 1 second GUI lag before responding to user events. But if you can live with it, this solution is probably an easiest to implement and even Qt endorses it in their Threading Basics article (see When to Use Alternatives to Threads section).
we can use following method QT_Delay
:
QTimer::singleShot(2000,this,SLOT(print_lcd()));
This will wait for 2 seconds before calling print_lcd()
.
참고URL : https://stackoverflow.com/questions/3752742/how-do-i-create-a-pause-wait-function-using-qt
'IT Share you' 카테고리의 다른 글
android : textAllCaps =“false”가 TabLayout 디자인 지원에서 작동하지 않음 (0) | 2020.11.15 |
---|---|
Mac OS X의 clock_gettime 대안 (0) | 2020.11.15 |
임의의 값으로 배열 만들기 (0) | 2020.11.15 |
빈 폴더 구조 커밋 (git 사용) (0) | 2020.11.15 |
NotImplementedException이 존재하는 이유는 무엇입니까? (0) | 2020.11.15 |