Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > С/С++: Кроссплатформенное программирование, Qt/Gtk+/wxWidgets > [Qt] аналог QApplication::processEvents()


Автор: anatox91 17.10.2011, 13:25
у меня в классе виджета выполняются определенные действия в цикле, и в этом же классе на форме есть пару кнопок и надо чтобы при нажатии на них выполнялись слоты, допустим после каждой итерации цикла мне нужно как-то выполнить все слоты, которые были вызваны(были поставлены в очередь на выполнение)
и все это не прерывая цикла, желательно без потоков
QApplication::processEvents() очень хорошая вещь, то что нужно, но она выполняет только накопившиеся event'ы, а мне нужно тоже самое но для сигналов и слотов

вот кусок кода чтобы понять о чем речь
Код

void Emulator::on_playButton_clicked() {
    isPaused = false;
    isStopped = false;
    while(!isPaused || !isStopped || nextByte < instructions_set.size()) {
        decode_next(nextByte);
        curInstrNumber++;
        QApplication::processEvents();
        for(int i=0; i<delay; ++i) {
            Sleep(1000);
        }
    }
}

void Emulator::on_pauseButton_clicked() {
    isPaused = true;
}

void Emulator::on_stopButton_clicked() {
    isStopped = true;
    nextByte = 0;
}

void Emulator::on_stepButton_clicked() {
    if(isPaused || isStopped) {
        decode_next(nextByte);
        curInstrNumber++;
    }
}



допустим запускается play, и надо чтобы в течение выполнения можно было поставить на паузу или остановить выполнение

Автор: null56 17.10.2011, 14:10
Цитата

в этом же классе на форме есть пару кнопок и надо чтобы при нажатии на них выполнялись слоты, допустим после каждой итерации цикла мне нужно как-то выполнить все слоты, которые были вызваны(были поставлены в очередь на выполнение)


Цитата

и все это не прерывая цикла, желательно без потоков

без потоков никак, ибо у тебя один поток на всё, на обработку слотов, событий и цикла. postEvent ставит в очередь и сразу возвращает управление, если у тебя цикл будет бесконечным, даже она тебя не спасет, потому что надо вернуться в eventloop, чтобы выполнить твои события

ну это на сколкьо мне известно

Добавлено через 3 минуты и 9 секунд
что же касается твоего вопроса, то на сколько мне известно есть сигналы, которые тут же не выполняются, а откладываются до возврата в eventloop, как тебе и нужно
Код

bool QObject::connect ( const QObject * sender, const char * signal, const QObject * receiver, const char * method, Qt::ConnectionType type = Qt::AutoConnection ) [static]

последний параметр
Цитата

enum Qt::ConnectionType
This enum describes the types of connection that can be used between signals and slots. In particular, it determines whether a particular signal is delivered to a slot immediately or queued for delivery at a later time.
Constant    Value    Description
Qt::AutoConnection    0    (default) If the signal is emitted from a different thread than the receiving object, the signal is queued, behaving as Qt::QueuedConnection. Otherwise, the slot is invoked directly, behaving as Qt::DirectConnection. The type of connection is determined when the signal is emitted.
Qt::DirectConnection    1    The slot is invoked immediately, when the signal is emitted.
Qt::QueuedConnection    2    The slot is invoked when control returns to the event loop of the receiver's thread. The slot is executed in the receiver's thread.
Qt::BlockingQueuedConnection    4    Same as QueuedConnection, except the current thread blocks until the slot returns. This connection type should only be used where the emitter and receiver are in different threads. Note: Violating this rule can cause your application to deadlock.
Qt::UniqueConnection    0x80    Same as AutoConnection, but the connection is made only if it does not duplicate an existing connection. i.e., if the same signal is already connected to the same slot for the same pair of objects, then the connection will fail. This connection type was introduced in Qt 4.6.
Qt::AutoCompatConnection    3    The default type when Qt 3 support is enabled. Same as AutoConnection but will also cause warnings to be output in certain situations. See Compatibility Signals and Slots for further information.

видимо тебе нужен
Qt::QueuedConnection

Добавлено через 6 минут и 10 секунд
хотя не, одно и тоже, что по умолчанию

Автор: anatox91 17.10.2011, 18:18
жалко, ладно придется чуть посложнее тогда сделать

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)