Use Scala to implement the Eventable interface of the Qt QWidget object

Source: Internet
Author: User

Today we will talk about how to use Scala to implement the Eventable interface of the Qt QWidget object. This Eventable interface is a commonly used item in my project. Scala emphasizes FP, but Qt Jambi itself is based on OOP and event overloading needs to be performed in the class. In the example shown above, we can see that a class is often expanded to be reloaded as follows:

 
  1. new QLabel {  
  2.   override def xxxxEvent  
  3. }  

This type of statement has many methods. In fact, it is easy for people to think that it is not standard, and reading is not easy. So I initiated the introduction of JavaScript code that declares the event style. js is a very fp language, and scala is also. Isn't that a good decision? Provide specific code:

 
  1. Package yourporject. package
  2.  
  3. Import scala. collection. mutable. {ArrayBuffer, HashMap}
  4. Import com. trolltech. qt. gui ._
  5. Import com. trolltech. qt. core ._
  6. Import com. trolltech. qt. core. QEvent
  7. Import com. trolltech. qt. QSignalEmitter ._
  8. Import com. agiers. mvc. Base
  9. /*
  10. * The Base class encapsulates method extensions for existing classes in Java and Scala, using implicit mixing without changing the object itself.
  11. * For example
  12. * "OnClick". toEventName => click
  13. * "Text". encode => url encode
  14. * "Traditional Chinese character". encodeSys => This is a character recognized by the root guest operating system.
  15. * "Traditional Chinese characters". toSimplified => traditional Chinese objects
  16. * "Simplified Chinese". toTraditional => simplified to traditional Chinese
  17. * "Hello_world". toCamelCase => HelloWorld
  18. * "Good guys". dump ("temp.txt") => input the string content to an io file.
  19. * "Hello world". md5 => encrypt the string md5
  20. */
  21.  
  22. Trait Eventable [T <: QWidget] extends QWidget with Base {
  23. // Define the closure format Declaration
  24. // All types that use closures in Eventable should first use the Fn type
  25. // Modify the closure type, which should be modified here, not in the specific declaration
  26. Type Fn = EventHandle => Unit
  27. // Define a combination of event types
  28. // This actually represents String-> Fn or (String, Fn)
  29. Type Ev = (String, Fn)
  30. /**
  31. * Event receiver object
  32. * It is used to take over the closure processing when declaring an event and temporarily store various states and variables in the closure.
  33. * @ TODO: gradually add its storage and read interfaces.
  34. * @ Author Janpoem
  35. */
  36. Sealed case class EventHandle (val widget: T, val event: QEvent ){
  37. // This is used to obtain the status when the widget executes the event.
  38. Private var _ break = false
  39. // The following
  40. Def isBreak = _ break
  41. Def isBreak _ = (is: Boolean) = _ break = is
  42. Def break (fn: EventHandle => Boolean) = isBreak = fn (this)
  43. }
  44. /**
  45. * Storage container of closures
  46. * The closure can be stored as a queue and executed sequentially in the fire.
  47. * @ Author Janpoem
  48. */
  49. Sealed case class FnContainer (fn: Fn ){
  50. Private var fns = ArrayBuffer [Fn] (fn)
  51. Def + (fn: Fn): this. type = {
  52. Fns + = fn
  53. This
  54. }
  55. Def fire (widget: T, event: QEvent): EventHandle = {
  56. Val handle = EventHandle (widget, event)
  57. Fns. foreach (_ (handle ))
  58. Handle
  59. }
  60. }
  61. // Define the helper for converting the Qt Standard Time type to the current class
  62. // Use lower case for name
  63. // @ TODO: Add QEvent. Type content continuously
  64. Private val _ eventsMap = HashMap [QEvent. Type, String] (
  65. QEvent. Type. Show-> "show ",
  66. QEvent. Type. MouseButtonPress-> "click ",
  67. QEvent. Type. MouseButtonDblClick-> "doubleclick ",
  68. QEvent. Type. FocusIn-> "focus ",
  69. QEvent. Type. FocusOut-> "blur ",
  70. QEvent. Type. Enter-> "enter ",
  71. QEvent. Type. Leave-> "leave"
  72. )
  73. // Event
  74. Private val _ events = HashMap [String, FnContainer] ()
  75.  
  76. // Pass in the QEvent. Type of Qt to obtain its quick helper name within Eventable.
  77. Def eventType2Name (_ type: QEvent. Type): Option [String] = _ eventsMap. get (_ type)
  78. // Load events
  79. // W. addEvent ("show", handle => {/**/})
  80. Def addEvent (s: String, fn: Fn): this. type = {
  81. Val name = s. toEventName
  82. If (! This. hasEvent (name ))
  83. _ Events (name) = FnContainer (fn)
  84. Else
  85. _ Events (name) + fn
  86. This
  87. }
  88. // W. addEvent ("click"-> {handle => println (handle. event )})
  89. Def addEvent (event: Ev): thisthis. type = this. addEvent (event. _ 1, event. _ 2)
  90. Def addEvents (events: Ev *): this. type = {
  91. Events. foreach (this. addEvent (_))
  92. This
  93. }
  94. // Determine whether an event exists
  95. Def hasEvent (name: String): Boolean = _ events. contains (name. toEventName)
  96. // Qt event coverage
  97. Override def event (event: QEvent): Boolean = {
  98. EventType2Name (event. 'type' () match {
  99. Case Some (name) =>
  100. If (this. hasEvent (name )){
  101. Val handle = _ events (name). fire (this. asInstanceOf [T], event)
  102. }
  103. Case _ =>
  104. }
  105. Super. event (event)
  106. }
  107. }

This Eventable is just a preliminary encapsulation, and is only applicable to all qwidgets. I still have some ideas, such as delayed event activation and scheduled event loop. In addition, it is expected that all qobjects can be used, and Qt signal slots must be compatible. Alas, there are too many ideas, but the time is too limited. Use it first. It's time to write event Declarations like writing JavaScript.

The following code is provided:

 
  1. Class Widget extends QWidget with Eventable [QWidget]
  2.  
  3. Val w = new Widget ()
  4. W. addEvent ("onClick", handle => {
  5. Println ("clicked! ")
  6. })
  7. W. addEvents (
  8. "Show"-> {handle =>
  9. Println ("displayed in the window ")
  10. },
  11. "DoubleClick"-> {handle =>
  12. Println ("double-click! ")
  13. }
  14. )
  15.  

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.