QT(4.8.2)GUI-自己的主循环,而不是qapplication :: exec()



我想问一下,是否可以使用自定义主循环而不是运行a.exec():

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Window r;
    r.showFullScreen();
    return a.exec(); 
}

类似:

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Window r;
    r.showFullScreen();
    while(a.processOneEvent()) {
        read_event_from_legacy_system
    }
    return 0; 
}

在gtk中,我可以使用 gtk_main_iteration_do(),所以我认为qt中可能有类似的东西?

或还有其他正确的方法可以从特定的旧系统中读取自定义事件?

编辑:从FIFOS读取的事件不是系统事件(例如X11),它们只是通过FIFO发送以实现IPC的结构。

,因此您想使用qt

在fifo -or -pipe -pipe -pipe -pipe -file -file -file -file -file -file -file -file -file -file -file -file -file -file -file -file -file -file -file -file -file -file -file -file -file -file -file -file-

使用QT5,您可能会使用Qabstractsocket或Qiodevice及其ReadyRead Signal

使用QT4,您应该使用QSocketNotifier及其激活信号(因此,请从连接到该信号的QT插槽调用read_event_from_legacy_system)。它可以轮询任何文件描述符,包括FIFO(7)

无需更改应用程序的事件循环(即使从理论上讲,您可能会亚类Qapplication,但我不建议这样做)。一旦正确设置您的设置,QT事件循环将poll附加文件描述符,您的代码应read IT。

尽管这可能不是解决问题的最佳解决方案,但您可以像这样编写自己的主循环:

QApplication app(argc, argv);
QMainWindow wnd;
wnd.show();
while(wnd.isVisible())
{
    app.processEvents();
    // perform your own actions here
}

而不是wnd.isvisible()您当然可以使用自己的破坏条件。

我提出了以下解决方案:

pipereader.hpp

#ifndef PIPEREADER_HPP
#define PIPEREADER_HPP
#include <QObject>
#include <QSocketNotifier>
class PipeReader : public QObject
{
    Q_OBJECT
public:
    PipeReader(int fd, QObject *parent = 0);
    ~PipeReader();
private:
    QSocketNotifier *notifier;
    int m_fd;
signals:
    void dataReceived();
private slots:
    void readFromFd();
};
#endif  /* PIPEREADER_HPP */

pipereader.cpp

#include <PipeReader.hpp>
#include <QObject>
PipeReader::PipeReader(int fd, QObject *parent)
: QObject(parent), notifier(NULL), m_fd(fd)
{
    notifier = new QSocketNotifier(m_fd, QSocketNotifier::Read, this);
    QObject::connect(notifier, SIGNAL(activated(int)), this, SLOT(readFromFd()));
}
PipeReader::~PipeReader()
{
}
void PipeReader::readFromFd()
{
    qDebug("readFromFd");
    int ret_val = read(m_fd, &event, sizeof(Event), 10);
    emit dataReceived();
}

main.cpp

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MyWindow w;
    if ((fd = open(SPECIAL_FD, O_RDONLY | O_SYNC)) < 0) {
        exit(0);
    }
    PipeReader reader(fd);
    w.showFullScreen();
    return a.exec();
}

我从特定的文件描述符中读取所有事件。如果要使用MyWindow中的事件,只需将信号DatareCeived()与MyWindow的公共插槽连接。

最新更新