사용자로부터 콘솔창을 통해 입력받기 위한 예제소스코드이다.
#ifdef Q_OS_WIN
#include <QWinEventNotifier>
#include <windows.h>
#else
#include <QSocketNotifier>
#endif
#include <iostream>
class Console : public QObject
{
Q_OBJECT
public:
Console(QObject *parent = nullptr):QObject(parent){}
void run()
{
std::cout << "Please input command." << std::endl;
std::cout << "> " << std::flush;
#ifdef Q_OS_WIN
m_notifier = new QWinEventNotifier(GetStdHandle(STD_INPUT_HANDLE));
connect(m_notifier, &QWinEventNotifier::activated, [&](HANDLE) {
#else
m_notifier = new QSocketNotifier(fileno(stdin), QSocketNotifier::Read, this);
connect(m_notifier, &QSocketNotifier::activated, [&](int) {
#endif
std::string line;
std::getline(std::cin, line);
if (std::cin.eof() || line == "quit") {
std::cout << "Good bye!" << std::endl;
emit quit();
} else {
std::cout << "Echo: " << line << std::endl;
std::cout << "> " << std::flush;
}
});
}
private slots:
signals:
void quit();
private:
#ifdef Q_OS_WIN
QWinEventNotifier *m_notifier;
#else
QSocketNotifier *m_notifier;
#endif
};
main.cpp
#include <QCoreApplication>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
Console console;
console.run();
// quit 시그널을 수신하면 종료
QObject::connect(&console, SIGNAL(quit()), &a, SLOT(quit()));
return a.exec();
}