QMessageBox show() not displaying text



  • Hi all -

    I need to inform the user that the device he's working on is temporarily unavailable. I'm trying to use a QMessageBox. This is the code:

            // ??? wait for debug messages to start before continuing.
            QMessageBox messageBox;
            messageBox.setText("Please wait while the target resets.");
    //        messageBox.setModal(true);
    //        messageBox.show();
            messageBox.exec();
    
            bool b = serial->waitForReadyRead(10000);
            sendDiscoveryRequest();
    
            messageBox.done(0);
    

    This doesn't work as I want, because the exec() call doesn't return. But the message box looks fine. When I disable the exec() call, and use the setModal/show calls, the behavior is good, but my message box is empty (doesn't have the text or the OK button). Any idea why?

    If there's a better method for doing this, I'm open to suggestion. The only requirement is that the message should be dismissable either by the user, or by the program.



  • I'm surprised it's shown at all. serial->waitForReadyRead(10000); blocks the event loop and if you return from that method (to the event loop) the messagebox is deleted.

    QMessageBox* messageBox=new QMessageBox(this);
    messageBox->setText("Please wait while the target resets.");
    connect(serial,SIGNAL(readyRead()),this,SLOT(sendDiscoveryRequest()));
    connect(serial,SIGNAL(readyRead()),messageBox,SLOT(deleteLater()));
    messageBox->show();
    

    P.S.
    if you want connect(serial,SIGNAL(readyRead()),this,SLOT(sendDiscoveryRequest())); to disconnect when messagebox is closed you can use Qt5 connection syntax, use messageBox as context and a lambda [this]()->void{sendDiscoveryRequest();} as slot



  • @VRonin thank you for the code fragment. It doesn't seem to be working quite right yet...the sendDiscoveryRequest() slot never seems to get called. Any idea what might be blocking its delivery?

    As clarification for what I'm trying to do, when I enter this code, I need the application to "sleep" until readyRead() is called. This is true whether or not the user dismisses the message box.

    EDIT: please disregard the first paragraph. I'd forgot to re-declare sendDiscoveryRequest() as a slot.


  • Moderators

    @mzimmers Why does your app need to "sleep"? Your app already has an event loop, so the slot will be called as soon as the signal is emitted.



  • @jsulm The target device, upon receiving a particular command, sends a response to me and then goes into a reset mode. During the first ~10 seconds of this reset mode, the device goes completely silent and accepts no input. After this initial period, the device begins transmitting status messages and will accept certain commands. For another ~30 seconds, the device "appears" active, but is still not capable of accepting all commands.

    I want my app to wait for the end of the initial (10 second) period by remaining idle until it receives the first of those status messages. I also want to alert the user that during this period, none of his commands will work.

    Incidentally, there's a problem with VRonin's above solution: I don't want to send a discovery request to every read, because 1) the reads are buffered and I don't always get a complete message and 2) some of the reads call for different requests to go out. This is handled elsewhere in the program.



  • @mzimmers

    Try this one:

    QTime t;
    t.start();
    QMessageBox messageBox;
    messageBox.setText("Please wait while the target resets.");
    
    messageBox.exec();
    
    bool b = serial->waitForReadyRead(10000- t.elapsed() > 10000 ? 10000 : t.elapsed());
    sendDiscoveryRequest();
    

    QMessageBox::exec is a blocking call, so everything after the call is executed when the MessageBox is closed. But the Qtime element will still run.

    If you want to automatically close the dialog box after 10 seconds, to resume your program, thats more complicated.



  • @J.Hilk yeah, ideally the message would self-dismiss when the device reset has completed. Perhaps I shouldn't be using a message box (or any dialog) for this, but should be indicating this in the UI itself?



  • @mzimmers
    of course, idealy creating your own "Custom MessageBox" is the way I would go, and have gone in the past.

    However if you're feeling lazy, you can try this, its untested, but should work.

    QTime t;   
    t.start();
    QMessageBox messageBox;
    messageBox.setText("Please wait while the target resets.");
    
    QTimer::singleShot(10000, &messageBox, QMessageBox::close);
    messageBox.exec();
    
    bool b = serial->waitForReadyRead(10000- t.elapsed() > 10000 ? 10000 : t.elapsed());
    sendDiscoveryRequest();
    

  • Qt Champions 2016

    @mzimmers said in QMessageBox show() not displaying text:

    yeah, ideally the message would self-dismiss when the device reset has completed. Perhaps I shouldn't be using a message box (or any dialog) for this, but should be indicating this in the UI itself?

    What you need in fact is a state machine to represent the device's states and to notify you in an asynchronous fashion of state changes. Then you can tie those signals to your dialog or UI or w/e.



  • @kshegunov funny you should mention that -- I was just coming to the same realization. Now I have to decide whether I need a full blown state machine, or if I can just fake it with a member variable in the device object that is set by the worker upon various occurrences.

    I'd just finished writing this when you posted:

    enum DevStates
    {
        UNKNOWN,        // this value used when the app starts
        RUNNING,        // this is the "normal" state
                        // entered after receiving a discovery response
                        // exits after receiving a change confirmation
        WAITING,        // the device enters this state upon receiving
                        // a change command (and sending a response)
                        // exits this state after a ~5 second timeout
        RESETTING       // the device enters this state after the timeout
                        // exits when it responds to a disovery request.
    };
    

  • Qt Champions 2016

    @mzimmers said in QMessageBox show() not displaying text:

    Now I have to decide whether I need a full blown state machine, or if I can just fake it with a member variable in the device object that is set by the worker upon various occurrences.

    The latter is the former. :)
    The simplest state machine is an ordinary switch (or if-else cascade) which modifies a "state" variable depending on the input you feed it. You'd feed the different messages/or hw events you get into the machine and it'd reflect that in the state.


  • Qt Champions 2016

    Hi
    Since you only have one device with few States,
    switch case will work pretty well as
    something like
    http://digint.ch/tinyfsm/doc/introduction.html
    is most likely overkill for such simple machine.
    (Qt also have http://doc.qt.io/qt-5/qstate.html#details )

    However, an object orientated approach makes it easier to add test code and extra conditions
    on transit and will in general be more solid with future features added.

    but in my experience, if only a few states and few possible paths, a switch case and
    function to handle the transits is just right as using a Full State system is pretty verbose.



  • @mrjj thanks for the link. I tend to agree that for this program, a true state machine is overkill (though I will probably need one in a few weeks on another project). This project has been a learning experience for me on a few levels: it's really the first time I've tried to do anything with Qt, it's my first attempt at OOD and I'm using some data structures for the first time. Lots of opportunity for mistakes.

    Currently I'm trying to run a timer at most once a second. Here's a code fragment:

                if (devState == RESETTING)
                {
                    if (timer.isActive()) // only do one at a time.
                    {
                        qDebug() << "\t\ttimer already queued.";
                    }
                    else
                    {
                        timer.singleShot(1000, this, SLOT(sendDiscoveryRequest()));
                        qDebug() << "\t\tqueueing timer.";
                    }
                }
    

    This code is inside a slot function that is called whenever the target writes to the host. I never hit the "timer already queued". Am I misusing the singleshot feature?


  • Qt Champions 2016

    Hi
    Normally you use the static version of singleshot

    QTimer::singleShot(1000, this, SLOT(timerDone()));

    It requires no instance.

    But seems you need an instance for others checks so a variable should be fine.

    so when u send DiscoveryRequest, can it also timeout ?



  • @mrjj are you asking if the sendDiscoveryRequest() routine might be timing out? That's unlikely...it just writes a short byte array to the serial port and flushes it.


  • Qt Champions 2016

    @mzimmers
    Oh, sorry for being unclear,
    i mean, do u need to be able to have a timeout on each command if no answer is received ?
    Often it goes
    SendCMD
    OnReplyDo/ TimeOut-> restart sequence.



  • @mrjj I'm still not sure I understand your question, so let me give some supplementary information.

    In normal operation, the host forms requests and sends them to the target, then reads a response from the target. Unfortunately, the target also spews out unsolicited (and unwanted messages) when in a certain state. During the first 10-15 seconds of this state, the target will ignore any input from the host. After this 10-15 second period, the target will listen for requests. A discovery request will cause the target to cease sending the (unwanted) debug messages.

    Because the messages are binary and encrypted, there's no way of knowing at first glance whether I've received a "real" response, or just the debugger output. My solution is, when the target is in the "resetting" state, send it a discovery request every second, until I get a valid discovery response. THAT is what I'm trying to do with my timer.

    I don't "wait" for responses to my requests; I just process any serial input with a slot.

    I don't know whether this answers your question or not...


  • Qt Champions 2016

    @mzimmers
    Yes that a very nice explanation.
    Its seems like a valid approach.
    Sometimes i use a list of small classes to hold each state, and use
    virtual function to make sure i dont get too many if structures

    But i wonder one thing
    timer.singleShot(1000, this, SLOT(sendDiscoveryRequest()));

    so you call sendDiscoveryRequest one time. will it then start the timer again?



  • The sendDiscoveryMessage() call is a "kick start" to the communications process. One of two things will happen:

    • the target is in running state, and will respond with a valid response. In this case, no new timer is desired.
    • the target is in resetting state, and will not respond, BUT will continue to send those spurious debug messages. When it sends one of these, the routine the above code is in is invoked (as a slot).

    So, in either case, the host will receive some input from the target, and normal processing can continue.

    These debug messages can come very quickly, and I don't wish to respond to each with a discovery request. This is the purpose of the timer -- to "gate" my requests. But...it's not working, as timer.isActive() never returns true.


  • Qt Champions 2016

    @mzimmers

    • timer.isActive() never returns true.
      Well if it takes more than 1 sec before the containing slot is called again then is it then not true that timer.isActive() is false?
      also the single shot might not even set active. maybe only start() does.
      (just speculating)


  • @mrjj said in QMessageBox show() not displaying text:

    Well if it takes more than 1 sec before the containing slot is called again then is it then not true that timer.isActive() is false?

    If it takes more than 1 second (which it never does), the isActive should report false, and a new singleShot should be called. At least that's what I'm attempting to do.

    also the single shot might not even set active. maybe only start() does.
    (just speculating)

    Interesting...I'll replace the singleShot with a conventional timer and report back.


  • Qt Champions 2016

    singleShot is a static function, it calls setSingleShot(true) and then start(). As this function doesn't really require an object it also does not modify your object in any way, effectively you're calling QTimer::singleShot.

    PS.
    Use like this:

    timer.setSingleShot(true);
    QObject::connect(&timer, &QTimer::timeout, this, &WhateverYourClassIsNamed::sendDiscoveryRequest);
    // ...
    if (devState == RESETTING)  {
        if (timer.isActive()) // only do one at a time.
            qDebug() << "\t\ttimer already queued.";
        else  {
            timer.start(1000);
            qDebug() << "\t\tqueueing timer.";
        }
    }
    


  • OK, I found why the timer wasn't working for me. It turns out I defined the QTimer * variable twice: once as a member of my Worker class, and once again in the Worker constructor. General hilarity ensued.

    I'm not saying this wasn't my fault, but I'd have expected the damn compiler to at least give me a warning when I did this.

    Thanks to all for the help on the QTimer. Now that my communications sequence is intact, I can review my approach to the original problem with the QMessageBox. I'll report back when I have something.


  • Qt Champions 2016

    @mzimmers said in QMessageBox show() not displaying text:

    I'm not saying this wasn't my fault, but I'd have expected the damn compiler to at least give me a warning when I did this.

    Not a thing that warrants a warning. Shadowing is a normal feature of the language, and you can see it quite a lot in my code. Without this I'd get a ton of warnings for correct usage of a valid language construct. For example for a generic QObject subclass (a situation that happens all the time):

    class MyClass : public QObject
    {
    public:
        MyClass(QObject * parent = nullptr) //< `parent` shadows QObject::parent()
            : QObject(parent)
        {
        }
    };
    

    Or even more elaborate:

    void QMpiCompoundRequestPrivate::requestFinished(QMpiRequest * child)
    {
        if (!subrequests.remove(child))
            return;
    
        Q_Q(QMpiCompoundRequest);
        emit q->finished(child);
        if (subrequests.size() == 0)
            emit q->QMpiRequest::finished();
    }
    

    See how the second signal emission is done. That's because in the derived class (QMpiCompoundRequest) there's a function that shadows the base class' (QMpiRequest) method (even though with different set of parameters). So in this case you must be explicit which function exactly you're calling.



  • @kshegunov thanks for the explanation. I had never seen shadowing before, probably because I'd done very little work with derived classes. Good stuff to know going forward.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.