In one of my mobile QML applications, I need to know when the handset orientation changes. The runtime knows but it doesn’t offer a signal to my code. Here is a QML hack that observes when orientation changes. It watches both height and width for changes. When they have both changed, it sets a boolean property to ‘true’. This works on handsets because both height and width change when orientation changes. It probably won’t work on a desktop because there it’s easy to change one without the other.

  1.    
  2. /*
  3.     Hack to observe changes in orientation from portrait to landscape in a Rectangle.
  4.    
  5.     Observation: On handsets, both the width and the height of the
  6.     Rectangle will change when orientation changes.  There is no way to
  7.     catch both changes at the same time, so we catch them individually
  8.     and set corresponding bools so we can remember the events.  When we
  9.     observe that both flags are 'true', we determine the orientation
  10.     and set both bools back to 'false'.
  11. */
  12. property bool changeOfWidth: false
  13. property bool changeOfHeight: false
  14. property bool newOrientation:  false
  15.  
  16. onWidthChanged: {changeOfWidth = true; newOrientation = (changeOfWidth && changeOfHeight)}
  17. onHeightChanged: {changeOfHeight = true; newOrientation  = (changeOfWidth && changeOfHeight)}
  18.  
  19. onNewOrientationChanged: {
  20.     if (newOrientation) {
  21.         changeOfWidth = false;
  22.         changeOfHeight = false;        
  23.        
  24.         if (width > height) {
  25.             // landscape
  26.             console.log("landscape")
  27.         } else {
  28.             // portrait
  29.             console.log("portrait")
  30.         }
  31.     }
  32. }

Categories: