简体   繁体   中英

Qt Signals/Slots Changeable?

I have been writing some basic applications with Qt, and have found its signals and slots mechanism to be very helpful. However, there is something I am hoping to do, but I can't seem to figure out how to make it work.

Basically, I want to have a screen with some text, pictures, whatever and a block of buttons. When I push a button, I want the other stuff on screen to change accordingly. Then I want to repeat the process. The application I am thinking of works similar to a basic text-based game.

I am hoping to write something like this:

void someFunction()
{
    //Display some stuff
    if(button1pressed())
    {
        //display some different stuff
        if(button1pressed())
        {
             ...
        }
        if(button2pressed())
        {
            ...
        }
        if(button...pressed())
        {
           ...
        }
    }
    if(button2pressed())
    {
        //display some different stuff
        if(button1pressed())
        {
             ...
        }
        if(button2pressed())
        {
            ...
        }
        if(button...pressed())
        {
           ...
        }
   }
    if(button...pressed())
    {
        //display some different stuff
        if(button1pressed())
        {
             ...
        }
        if(button2pressed())
        {
            ...
        }
        if(button...pressed())
        {
           ...
        }
   }
}

Is there a way to nest button presses like this? Or another way to accomplish the same idea? Thanks!

Too much nested "if" statements is not a good idea. For the readability of the code, and for the future if you want to update your software. This is always simple at the beginning but it tends to be complicated then... You can use the state pattern which allows you to change the behavior of a object depending on actions taken. Each call of a button will change the internal state of an object, and the way this change is done can depend on the current internal state. For example:

  • Initial state is "1"
  • From state "1", triggering button "A" leads to the state "2"
  • From state "2", triggering button "A" leads to the state "3"
  • From state "3", triggering button "B" reinitializes to the state "1"

Edit: as stated by Kuba, QStateMachine is a class helping you in this process.

Another idea would be to store the order of the buttons pressed. Connect each press event to a slot ( QSignalMapper can help), and store the order in a list. Then process the list and do actions accordingly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM