Our text editor is not a text editor if it didn't contain an editable text area. QML's TextEdit element allows the declaration of a multi-line editable text area. TextEdit is different from a Text element, which doesn't allow the user to directly edit the text.
TextEdit{ id: textEditor anchors.fill:parent width:parent.width; height:parent.height color:"midnightblue" focus: true wrapMode: TextEdit.Wrap onCursorRectangleChanged: flickArea.ensureVisible(cursorRectangle) }
The editor has its font color property set and set to wrap the text. The TextEdit area is inside a flickable area that will scroll the text if the text cursor is outside the visible area. The function ensureVisible() will check if the cursor rectangle is outside the visible boundaries and move the text area accordingly. QML uses Javascript syntax for its scripts, and as previously mentioned, Javascript files can be imported and used within a QML file.
function ensureVisible(r){ if (contentX >= r.x) contentX = r.x; else if (contentX+width <= r.x+r.width) contentX = r.x+r.width-width; if (contentY >= r.y) contentY = r.y; else if (contentY+height <= r.y+r.height) contentY = r.y+r.height-height; }
We are now ready to create the layout of our text editor using QML. The text editor has two components, the menu bar we created and the text area. QML allows us to reuse components, therefore making our code simpler, by importing components and customizing when necessary. Our text editor splits the window into two; one-third of the screen is dedicated to the menu bar and two-thirds of the screen displays the text area. The menu bar is displayed in front of any other elements.
Rectangle{
id: screen
width: 1000; height: 1000
//the screen is partitioned into the MenuBar and TextArea. 1/3 of the screen is assigned to the MenuBar
property int partition: height/3
MenuBar{
id:menuBar
height: partition
width:parent.width
z: 1
}
TextArea{
id:textArea
anchors.bottom:parent.bottom
y: partition
color: "white"
height: partition*2
width:parent.width
}
}
By importing reusable components, our TextEditor code looks much simpler. We can then customize the main application, without worrying about properties that already have defined behaviors. Using this approach, application layouts and UI components can be created easily.
[Missing image qml-texteditor3_texteditor.png]