Qt5/QML - Pagination in Text/TextArea - qt

Let's say I have a QML Text or TextArea that contains a very long HTML page. I want to make it easier to read by splitting it into pages.
More specifically, every time I press the down key, I want it to scroll down until none of the current text on the screen is still there.
I already know how to make the entire TextArea scrollable; that's not what I'm looking for. What I'm looking for is more like the kind of behavior you'd expect in an ebook reader.
Is there any way to do something like that, preferably in pure QML (though C++ is also fine).

You can measure the TextArea height after loading, divide it to the container height and so get the count of pages. Then you just move the TextArea relative to its container according to the current page.
The simple illustration of my idea:
import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Controls 2.5
import QtQuick.Layouts 1.3
Window {
id: main
visible: true
width: 640
height: 800
property int currentPage: 1
property int pageCount: 1
ColumnLayout
{
anchors.fill: parent
anchors.margins: 5
RowLayout {
Layout.preferredHeight: 40
Layout.alignment: Qt.AlignHCenter
Button {
text: "<"
onClicked: {
if(main.currentPage > 1)
main.currentPage --;
}
}
Text {
text: main.currentPage + " / " + main.pageCount
}
Button {
text: ">"
onClicked: {
if(main.currentPage < main.pageCount)
main.currentPage ++;
}
}
}
Rectangle {
id: container
clip: true
Layout.fillHeight: true
Layout.fillWidth: true
TextArea {
id: msg
text: "Loading ..."
width: container.width
height: container.height
y: -(main.currentPage - 1) * container.height
textFormat: TextEdit.RichText
wrapMode: TextEdit.Wrap
Component.onCompleted: {
msg.makeRequest();
}
onContentHeightChanged: {
msg.height = msg.contentHeight;
if(msg.contentHeight >= container.height && container.height > 0)
{
main.pageCount = msg.contentHeight / container.height;
loader.running = false;
}
}
function makeRequest()
{
var doc = new XMLHttpRequest();
msg.text = "";
doc.onreadystatechange = function() {
if (doc.readyState === XMLHttpRequest.DONE) {
msg.text = doc.responseText;
}
}
doc.open("GET", "http://www.gutenberg.org/files/730/730-h/730-h.htm");
doc.send();
}
}
}
}
BusyIndicator {
id: loader
running: true
anchors.centerIn: parent
}
}
Of course you have to process margins, the last line on a page, recalculate the values on resizing etc.

Related

QML Video element randomly disappears on Label text change

I'm working on an app which is supposed to display a camera stream from a webcam. It's a single-page app which only shows a Video QML element showing the stream (which currently is a simple .avi file) and a Label element indicating the current connection state from an MQTT connection.
Here's the code:
import QtQuick 2.15
import QtQuick.Window 2.15
import QtQuick.Controls 2.1
import QtQuick.Layouts 1.1
import QtMultimedia 5.12
import MqttClient 1.0
Window {
width: 360
height: 640
visible: true
title: qsTr("Doorbell")
MqttClient {
id: client
// TODO
property string _host: "localhost"
property string _port: "1883"
property string _topic: "my/topic"
hostname: _host
port: _port
Component.onCompleted: {
connectToHost()
}
onConnected: {
subscribe(_topic)
}
onMessageReceived: {
video.play()
}
Component.onDestruction: {
disconnectFromHost()
}
}
GridLayout {
anchors.fill: parent
anchors.margins: 10
columns: 2
Video {
id: video
objectName: "vplayer"
width: parent.width
height: 300
Layout.columnSpan: 2
autoPlay: false
source: "file:///path/to/my/test.avi"
onErrorChanged: {
console.log("error: " + video.errorString)
}
MouseArea {
anchors.fill: parent
onClicked: {
video.muted = !video.muted
}
}
focus: true
Image {
id: muteIndicator
source: "mute_white.png"
width: 64
height: width
visible: video.muted
anchors.centerIn: parent
}
}
Label {
function stateToString(value) {
if (value === 0)
return "Disconnected"
else if (value === 1)
return "Connecting"
else if (value === 2)
return "Connected"
else
return "Unknown"
}
Layout.columnSpan: 2
Layout.fillWidth: true
text: stateToString(client.state) + "(" + client.state + ")"
}
}
}
Here's a screenshot:
Here's the clue:
I tried removing the Label and replacing it with a simple rectangle indicator (red or green) to show if the connection is currently active.
However, when replacing the text content of the Label element, the Video element completely disappears.
What I've tried:
removing the stateToString(client.state) + "(" + client.state + ")" part and replacing it with text: "Connected(2)"
replacing stateToString(... with an empty string (text: "")
replacing the content of stateToString(...) with return "Connected(2)"
and a lot of different more seemingly completely useless things
Example code:
// ...
Label {
function stateToString(value) {
if (value === 0)
return "Disconnected"
else if (value === 1)
return "Connecting"
else if (value === 2)
return "Connected"
else
return "Unknown"
}
Layout.columnSpan: 2
Layout.fillWidth: true
text: "Connected(2)"
// enabled: client.state === MqttClient.Connected
}
// ...
Unless I set text to the exact value stateToString(client.state) + "(" + client.state + ")" or at least stateToString(client.state), the Video element will always disappear in the QML view:
I have no idea of what might be the reason for this.
Any help is greatly appreciated, thanks.
Try adding:
Layout.fillWidth: true
after:
objectName: "vplayer"
I'm 99% sure the root of the problem is in the way you have used the layouts. In another word, you have not placed your QML elements in a robust way. since QML has so much flexibility in positioning elements in UI, it matters in QML to put your elements in a well-defined, robust way.

Load SwipeView pages dynamically

I have created the following MWE (Qt 5.13.0):
import QtQuick 2.0
import QtQuick.Window 2.2
import QtQuick.Controls 2.3
ApplicationWindow
{
property int itemsNo: 3;
id: window
visible: true
width: 480
height: 480
SwipeView
{
anchors.fill: parent;
id: theSwipeView;
Loader
{
sourceComponent: theSingleComp;
Component
{
id: theSingleComp;
Page
{
Text
{
text: "The single one";
}
}
}
}
Repeater
{
model: itemsNo;
Loader
{
sourceComponent: theMultiComp;
Component
{
id: theMultiComp;
Page
{
Text
{
text: "The multi one " +
(theSwipeView.currentIndex - 1);
}
}
}
}
}
}
}
In my program, I have an unique component (theSingleComp) and multiple components behind him (theMultiComp). As for now, I need to implement the following functionality:
In case the model used for theMultiComp has only 1 item, display only this item and not the theSingleComp. In case the are more theMultiComp items, display it like now. It seems to me that there is no possibility for this to work if I keep the items defined statically. But on the other hand, I don't know how to do this dynamically, since there is a case in which one of the components should not be displayed at all. I tried an approach like this:
sourceComponent: (itemsNo > 1) ? theSingleComp : null;
But then the page for this null component is still created.
Your problem is that Loader is an Item and SwipeView creates a page for it even if it doesn't have a source component.
To solve this problem you can use Repeater instead with a model of 1 (or 0 to disable it). Repeater is also an Item but it has some special code under the hood to be ignored by containers.
import QtQuick 2.0
import QtQuick.Window 2.2
import QtQuick.Controls 2.3
ApplicationWindow
{
id: window
property int itemsNo: 0
visible: true
width: 480
height: 480
SwipeView {
id: theSwipeView
anchors.fill: parent
Repeater {
model: window.itemsNo > 1 ? 1 : 0
Page {
Text {
text: "The single one"
}
}
}
Repeater {
model: window.itemsNo
Page {
Text {
text: "The multi one " + model.index
}
}
}
}
}
(I've simplified your code to remove the explicit Components and the Loaders)
I have come up with the following solution but I am not happy with it. It's very hacky and the user can see how the page index changes.
import QtQuick 2.0
import QtQuick.Window 2.2
import QtQuick.Controls 2.3
ApplicationWindow
{
property int itemsNo: 2;
id: window
visible: true
width: 480
height: 480
SwipeView
{
anchors.fill: parent;
id: theSwipeView;
Component.onCompleted:
{
if (itemsNo > 1)
insertItem(0, theSingleComp);
set0IndexTimer.start();
}
Timer
{
id: set0IndexTimer;
interval: 1;
running: false;
repeat: false;
onTriggered: theSwipeView.setCurrentIndex(0);
}
onCurrentIndexChanged: console.log("page: ", currentIndex);
Repeater
{
model: itemsNo;
Loader
{
sourceComponent: theMultiComp;
Component
{
id: theMultiComp;
Page
{
Text
{
text: "The multi one " + theSwipeView.currentIndex;
}
}
}
}
}
}
Item
{
id: theSingleComp;
Page
{
Text
{
text: "The single one";
}
}
}
}
I am still seeking some other examples.

get cursor position in WebEngineView qml

I have a program in Qt and a WebEngineView in it .I want to when my user clicked on a inputbox in webEngine a keyboard have been loaded and the inputbox get its contents from my keyboard (i wrote my own keyboard) but i can't do it .i try codes in bellow but don't work
WebEngineView {
anchors.fill:parent
id:webEng
url: "https://example.com"
visible: true
MouseArea {
id : mousearea
anchors.fill: parent
onClicked: {
mykeyboard.visible=true;
}
}
}
This is not a complete answer but this code could help:
import QtQuick 2.10
import QtWebView 1.1
import QtQuick.Controls 1.4
import QtWebEngine 1.7
Item {
width: 1280
height: 720
WebView { // or WebEngineView {
id: webview
width: 1280
height: 720
url: "http://google.com"
visible: true
onLoadingChanged: {
if (loadRequest.status === WebView.LoadSucceededStatus) {
console.log("Loaded!!")
webview.runJavaScript('
var input = document.getElementById("lst-ib");
input.addEventListener("click", function() {
alert("Clicked!");
});
'
)
}
}
}
Rectangle {
id: myDummyKeyboard
anchors.bottom: parent.bottom
width: parent.width
height: 100
color: "gray"
visible: true
border.width: 20
Button {
anchors.centerIn: parent
text: "Dummy"
onClicked: {
webview.runJavaScript('document.getElementById("lst-ib").value += "' + text + '"');
}
}
}
}
The part in the WebView (or WebEnginView) allows to display an alert when the input is clicked. But, something is missing, to link it to a QML handler. The solution is maybe to use WebChannel or maybe WebEngineScript as said by #folibis in the comments.
The part defined by myDummyKeyboard allows to add a string into the input when the user is clicking the button in the rectangle (fake keyboard).

How to center dialog on screen in QtQuick Controls 2?

All my dialogs appear on the top left corner of screen instead of the center.
What is the best way to let the dialogs be placed automatically correct?
import QtQuick 2.7
import QtQuick.Controls 2.2
ApplicationWindow {
id: mainWindow
visible: true
width: 640
height: 480
title: qsTr("Hello World")
Component.onCompleted: {
showMessageBox('Hey this actually works!');
}
function showMessageBox(message) {
var component = Qt.createComponent("MessageDialog.qml")
if(component.status == Component.Ready) {
var dialog = component.createObject(mainWindow)
dialog.title = qsTr("Information")
dialog.text = message
dialog.open()
} else
console.error(component.errorString())
}
}
With a very simple MessageDialog.qml:
import QtQuick 2.7
import QtQuick.Controls 2.2
Dialog {
standardButtons: DialogButtonBox.Ok
property alias text : textContainer.text
Text {
id: textContainer
anchors.fill: parent
horizontalAlignment: Qt.AlignLeft
verticalAlignment: Qt.AlignTop
}
}
The documentation hints, that the Dialog is a descendent of Popup which has x/y-coordinates.
I think those would be a good start to position it.
To your avail:
parent.width - which should be the width of your window
width - which should be your Dialogs width
parent.height
height
Calculate the right positions, and you should be fine.
With this you can create a new base class CenteredDialog.qml
Dialog {
x: (parent.width - width) / 2
y: (parent.height - height) / 2
}
and then use CenteredDialog instead of Dialog all the time.
Further, for dynamic instantiation you might declare the Component in the file, and only set the properties upon instantiation using the component.createObject(parentObject, { property1Name : property1Value, property2Name : property2Value ... }) syntax.
You can set x/y position (like derM said), but you have to recalculate every size change of ApplicationWindow!
Here is another solution:
ApplicationWindow {
id: mainWindow
visible: true
width: 640
height: 480
title: qsTr("Hello World")
Component.onCompleted: {
showMessageBox('Hey this actually works!');
}
Item {
anchors.centerIn: parent
width: msgDialog.width
height: msgDialog.height
MessageDialog {
id: msgDialog
title: qsTr("Information")
visible: false
}
}
function showMessageBox(message) {
msgDialog.text = message
msgDialog.visible = true
}
UPDATE: with dynamic instantiation:
Item {
id: dialogParent
anchors.centerIn: parent
}
function showMessageBox(message) {
var component = Qt.createComponent("MessageDialog.qml")
if(component.status === Component.Ready) {
var dialog = component.createObject(dialogParent)
dialog.title = qsTr("Information")
dialog.text = message
dialog.open()
dialogParent.width = dialog.width
dialogParent.height = dialog.height
} else {
console.error(component.errorString())
}
}
For a generic code which works anywhere, including out of Window/ApplicationWindow, you should use Overlay parent :
Dialog {
parent: Overlay.overlay // <------- global Overlay object
readonly property int margin: 16
width: parent ? (parent.width / 2 - margin) : 128
height: content.height + margin
x: parent ? ((parent.width - width) / 2) : 0
y: parent ? ((parent.height - height) / 2) : 0
modal: true
Label {
id: content
...
}
}
As of Qt 5.12 you can use anchors.centerIn attached property.
Dialog {
anchors.centerIn: parent
// ...
}
Then it will be centered on its parent. If you want it to be centered on its window, just set its parent to Overlay.overlay.
anchors.centerIn: Overlay.overlay

Multi item swipedelegate

Edited due to insufficient intial posting.
Hi,
thanks for your help!
You're right, I guess it is better to include the whole file, in spite of the size:
import QtQuick 2.5
import QtQuick.LocalStorage 2.0
import QtQuick.Dialogs 1.2
import QtQuick.Controls 2.1
import QtQuick.Controls.Styles 1.4
import QtQuick.Window 2.0
import QtQuick.Controls.Material 2.1
import "./database.js" as Database
ApplicationWindow {
visible: true
width: 640
height: 480
id: appWindow
x: Screen.width / 2 - width / 2
y: Screen.height / 2 - height / 2
title: qsTr("Project Stats")
Material.theme: Material.Dark
ListModel {
id: projectModel
ListElement {
projectID: "123654"
manager: "Schneider"
sponsor: "3466"
}
}
Component {
id: projectDelegate
SwipeDelegate {
id: projectSwipeDelegate
width: parent.width
height: projectDelegateItem.implicitHeight
anchors.horizontalCenter: parent.horizontalCenter
spacing: 10
contentItem: Item {
id: projectDelegateItem
Text {
id: projectID_text
text: "Project ID: " + projectID
font.pointSize: 20
anchors.horizontalCenter: parent.horizontalCenter
font.weight: Font.Black
color: "white"
}
Text {
id: manager_text
text: 'Manager: ' + manager + " Sponsor: " + sponsor
anchors.top: projectID_text.bottom
anchors.horizontalCenter: parent.horizontalCenter
font.weight: Font.Thin
color: "lightgrey"
}
}
onClicked: {
console.log(index, projectModel.get(index).projectID)
if (swipe.complete)
projectModel.remove(index)
else {
//var component= Qt.createComponent("timepointsstackview.qml")
//var loadwin = component.createObject(appWindow)
//loadwin.selected_project = projectModel.get(index).projectID
// stackView.push(Qt.resolvedUrl("timepointsstackview.qml"), {properties: {selected_project: projectModel.get(index).projectID}})
stackView.push(component, {properties: {selected_project: projectModel.get(index).projectID}})
}
}
swipe.right: Label {
id: deleteLabel
text: qsTr("Delete")
color: "white"
verticalAlignment: Label.AlignVCenter
padding: 12
height: parent.height
anchors.right: parent.right
SwipeDelegate.onClicked: projectListView.model.remove(index)
background: Rectangle {
color: deleteLabel.SwipeDelegate.pressed ? Qt.darker("tomato", 1.1) : "tomato"
}
}
}
}
Item {
Component.onCompleted: {
Database.getDatabase()
Database.getProjects()
}
}
StackView {
id: stackView
anchors.fill: parent
// Implements back key navigation
focus: true
Keys.onReleased: if (event.key === Qt.Key_Back && stackView.depth > 1) {
stackView.pop();
event.accepted = true;
}
initialItem: Item {
width: parent.width
height: parent.height
ListView {
id: projectListView
anchors.fill: parent
clip: true
model: projectModel
delegate: projectDelegate
}
}
}
onClosing: {
if (Qt.platform.os == "android") {
close.accepted = false;
// if (stack.depth > 1) stack.pop();
}
}
}
Meanwhile I already had removed the row/column stuff, which I put in to get it working somehow though I started without it.
I also experimented with implicitheight before intially posting, but sadly to no avail. The above is my current code, though putting in
height: projectDelegateItem.implicitHeight
in that spot (probabaly not the correct one or the wrong reference? Had to change it from your suggestion as I already took out the row) leads to rendering in one spot only.
Thanks for your time so far and also if you still have the patience to give me a clue where to turn the screws...
Ok, first of all:
Take warnings serious. If qml tells you, you should not try to use anchors within rows or columns, don't do it!
QML Row: Cannot specify left, right, horizontalCenter, fill or centerIn anchors for items inside Row. Row will not function.
QML Column: Cannot specify top, bottom, verticalCenter, fill or centerIn anchors for items inside Column. Column will not function.
Also don't do it, if you can't see those warnings. It will mess up a lot.
A row automatically anchors all its children side by side to each other. A column does the same, just horizontraly. If you mess with it, everything breaks.
Frankly: I don't even understand why you use this strange Row/Column-Setup.
For your case it seems way better to just resort to anchoring. If you have reasons for that, why not take a grid?
Secondly: You need to specify a height for your delegate. Unfortunately it seems like, it does not calculate an implicit height.
The SwipeDelegate calculates its own implcitHeight based on the implicitHeight of its contentItem.
The problem is, that you don't assign the row (which has a proper implicitHeight) as the contentItem, but add it as a child instead.
Assigning it as contentItem would fix that for you.
Regarding your edit, and removal of the Row: The Item you use now does not calculate a implicitHeight based on its children. So you need to provide your calculation yourself.
This will set a proper height to your delegate, and your delegates won't overlap.
import QtQuick 2.0
import QtQuick.Window 2.0
import QtQuick.Controls 2.0
Window {
width: 1024
height: 800
visible: true
ListView {
width: 400
height: 800
model: ListModel {
ListElement { projectID: 0; manager: 'I'; sponsor: 'mom' }
ListElement { projectID: 1; manager: 'YOU'; sponsor: 'dad' }
ListElement { projectID: 1; manager: 'HE'; sponsor: 'auntie' }
}
delegate: SwipeDelegate {
id: projectSwipeDelegate
width: parent.width
// height: <--- provide a height, if the contentItem does not provide it.
contentItem: Row{ // <--- Add your content as contentItem.
id: rowProjectDelegate
anchors.horizontalCenter: parent.horizontalCenter
width: parent.width
Column {
id: column
// anchors.horizontalCenter: parent.horizontalCenter <--- Don't do that!
width: parent.width
Rectangle{ // If you don't want to have them in a column, they can't be siblings. If you want to, then you should.
height: 10
width: 250
color: "red"
Rectangle {
height: 10
width: 200
color: "blue"
}
}
Label {
id: projectID_text
text: "Project ID: " + projectID
font.pointSize: 20
font.weight: Font.Black
color: "white"
}
Label {
id: manager_text
text: 'Manager: ' + manager + " Sponsor: " + sponsor
// anchors.top: projectID_text.bottom <--- Don't do that!
font.weight: Font.Thin
color: "lightgrey"
}
}
}
}
}
}

Resources