QML-How-to Anonymously Access To TableView From Within Delegates? - qml

Using QML, I’m writing a custom itemDelegate and rowDelegate that I want to be able to use across any number of different TableView instances. As the code to follows shows, I’ve been able to accomplish this—but only in a way that I’m extremely dubious about it working in future (or previous, for that matter) releases of Qt. I’m currently using Qt 5.2.
Component {
id: tableRowDelegate
Rectangle {
height: 16
color: styleData.selected ? "#448" : (styleData.alternate? "#eee" : "#fff")
property TableView tableView
// The view is 8 levels up for the rowDelegate
Component.onCompleted: {
if (styleData.row > -1) // Not entirely sure why this is needed -- worse, I don't know why it works; it just does
tableView = parent.parent.parent.parent.parent.parent.parent.parent
}
// Other delegate code omitted for brevity
}
}
Component {
id: tableCellDelegate
Rectangle {
width: parent.width
height: parent.height
color: "transparent"
border.color: "#a3b3b3"
border.width: 1
radius: 5
property TableView tableView
// The View is 9 levels up for the itemDelegate
Component.onCompleted: {
tableView = parent.parent.parent.parent.parent.parent.parent.parent.parent
}
// Other delegate code omitted for brevity
}
}
Once these delegates are constructed, access to the enclosing TableView is trivial
(and anonymous) by prefixing the property or signal name with ‘tableView.’; i.e.
tableView.alternatingRowColors
. . . just for example.
Is there really no better way to access the view from within a delegate without
hard-coding the ancestry, as in the above examples, or worse: without hard-binding
explicitly to the id of the TableView?
Caveat: I haven't actually tested this to make sure it'll work with a 2nd TableView.
It does work with the one I'm testing with.
Thanks for any thoughts!
Wayne
UPDATE with the answer. Thanks again, mlvljr, for helping me brainstorm this through.
Inline, at the TableView level, I can use a Loader element as kind of a wrapper delegate to create the loose-binding with the "real" delegate; as follows:
rowDelegate : Loader {
property TableView tableView : itemsAcquiredList
property QtObject styleDataExported: styleData
sourceComponent: tableRowDelegate
}
Those properties defined in the Loader are then available to
my "real" delegate. I can copy-paste just that block into any other
TableView, change just the id assigned to the tableView property, and
then use it with my reusable delegate.
It turns out that when I use a loader to get my delegate, styleData, and
model are no longer available directly in the loaded delegate; hence the
need for the 'styleDataExported' property in the Loader (the tableView
property now provides access to the model). So, for extra sugar-coating,
I can add two property bindings inside the loaded delegate, as follows:
property QtObject styleData: styleDataExported
property var model : tableView.model
And viola! Now my delegate's code looks just like a real one, and I
can get all the properties, signals, and methods from the TableView
ancestor without ever using its 'id', and without ever making any
assumptions about the internal ancestry of a delegate.
I don't know much about the loader, or whether I'll incur a performance
penalty for doing this, but it does give me a clean separation and
loose-binding between the view and the delegate. For now, this is
exactly what I was looking for.
Update II: I have tested this with both an itemDelegate, and a rowDelegate,
and they both work as expected.

Related

Querying global mouse position in QML

I'm programming a small PoC in QML. In a couple of places in my code I need to bind to/query global mouse position (say, mouse position in a scene or game window). Even in cases where mouse is outside of MouseAreas that I've defined so far.
Looking around, the only way to do it seems to be having whole screen covered with another MouseArea, most likely with hovering enabled. Then I also need to deal with semi-manually propagating (hover) events to underlying mouseAreas..
Am I missing something here? This seems like a pretty common case - is there a simpler/more elegant way to achieve it?
EDIT:
The most problematic case seems to be while dragging outside a MouseArea. Below is a minimalistic example (it's using V-Play components and a mouse event spy from derM's answer). When I click the image and drag outside the MouseArea, mouse events are not coming anymore so the position cannot be updated unless there is a DropArea below.
The MouseEventSpy is taken from here in response to one of the answers. It is only modified to include the position as parameters to the signal.
import VPlay 2.0
import QtQuick 2.0
import MouseEventSpy 1.0
GameWindow {
id: gameWindow
activeScene: scene
screenWidth: 960
screenHeight: 640
Scene {
id: scene
anchors.fill: parent
Connections {
target: MouseEventSpy
onMouseEventDetected: {
console.log(x)
console.log(y)
}
}
Image {
id: tile
x: 118
y: 190
width: 200
height: 200
source: "../assets/vplay-logo.png"
anchors.centerIn: parent
Drag.active: mausA.drag.active
Drag.dragType: Drag.Automatic
MouseArea {
id: mausA
anchors.fill: parent
drag.target: parent
}
}
}
}
You can install a eventFilter on the QGuiApplication, where all mouse events will pass through.
How to do this is described here
In the linked solution, I drop the information about the mouse position when emitting the signal. You can however easily retrieve the information by casting the QEvent that is passed to the eventFilter(...)-method into a QMouseEvent and add it as parameters to the signal.
In the linked answer I register it as singleton available in QML and C++ so you can connect to the signal where ever needed.
As it is provided in the linked answer, the MouseEventSpy will only handle QMouseEvents of various types. Once you start dragging something, there won't be QMouseEvents but QDragMoveEvents e.t.c. Therefore you need to extend the filter method, to also handle those.
bool MouseEventSpy::eventFilter(QObject* watched, QEvent* event)
{
QEvent::Type t = event->type();
if (t == QEvent::MouseButtonDblClick
|| t == QEvent::MouseButtonPress
|| t == QEvent::MouseButtonRelease
|| t == QEvent::MouseMove) {
QMouseEvent* e = static_cast<QMouseEvent*>(event);
emit mouseEventDetected(e->x(), e->y());
}
if (t == QEvent::DragMove) {
QDragMoveEvent* e = static_cast<QDragMoveEvent*>(event);
emit mouseEventDetected(e->pos().x(), e->pos().y());
}
return QObject::eventFilter(watched, event);
}
You can then translate the coordinates to what ever you need to (Screen, Window, ...)
As you have only a couple of places where you need to query global mouse position, I would suggest you to use mapToGlobal or mapToItem methods.
I believe you can get cursor's coordinates from C++ side. Take a look on answer on this question. The question doesn't related to your problem but the solution works as well.
On my side I managed to get global coordinates by directly calling mousePosProvider.cursorPos() without any MouseArea.

How to show current selection QML TreeView?

I can show current selection QML ListView but similar thing doesn't work in TreeView.
Part of the problem is for TreeView it doesn't recognize index which is passed to delegate in case of ListView. I tried styleData.indexbut that doesn't work either.
rowDelegate: Item {
id: row_delegate
height: 40
Rectangle {
id: rectid
anchors.fill: parent
MouseArea {
id: mouse_area
anchors.fill: parent
onClicked: {
console.log("Row clicked " + rectid.styleData.index)
}
}
}
}
The output is:
qml: Row clicked undefined
As stated by the documentation, you have a set of properties within the namespace styleData that can be used for almost the same purposes from within a delegate.
As an example, you can set the text property of a label that is part of your delegate as it follows:
text: styleData.value
Where styleData.value is (documentation excerpt):
the value or text for this item
Similarly, you have:
styleData.pressed - true when the item is pressed
styleData.index - the QModelIndex of the current item in the model
styleData.hasChildren - true if the model index of the current item has or can have children
And so on... Please, refer to the documentation for the full list.
Be aware also of the note at the end of the documentation:
Note: For performance reasons, created delegates can be recycled across multiple table rows. This implies that when you make use of implicit properties such as styleData.row or model, these values can change after the delegate has been constructed. This means that you should not assume that content is fixed whenComponent.onCompleted is called, but instead rely on bindings to such properties.

How to access delegate properties in ListView using index

I want to access delegate properties in ListView. I've tried with contentItem but sometimes it's undefined.
Here is my code:
ListModel{
id: modeldata
ListElement{
name:"don"
rank:1
}
ListElement{
name:"shan"
rank:2
}
ListElement{
name:"james"
rank:3
}
ListElement{
name:"jeggu"
rank:4
}
}
Component{
id: delegateitem
Row {
property int count: rank
Rectangle{
width: 100
height: 50
Text{
anchors.centerIn: parent
text: name
}
}
}
}
ListView{
id: listview
focus: true
anchors.fill: parent
model: modeldata
delegate: delegateitem
onCurrentIndexChanged: {
console.log("position",currentIndex)
console.log("property",contentItem.children[currentIndex].count);
}
}
Problem invalid output at position 1
qml: position 0
qml: property 1
qml: position 1
qml: property undefined
qml: position 2
qml: property 2
qml: position 3
qml: property 3
#Teimpz didn't really explain it well. Especially since there are bunch of qt project and ubuntu touch qml examples and use cases where you manage dynamically created list elements using javascript, and that is why they have javascript methods and properties
In QML there is more a notion of parent than a child, which is common in html. In bigger projects it is recommended (as you can also see in qt examples and in docs http://doc.qt.io/qt-5/qtqml-javascript-expressions.html#functions-in-imported-javascript-files) to have js logic separate from qml elements so you do access and manage elements from outside rather than pollute you qml elements with js logic, but not in a way of looking for children elements, but rather exposing children elements that you need.
In your case you should just use currentItem, same as you use currentIndex, so currentItem.count will give you what you need.
And if you don't need current item at all, you can access elements from model directly:
modelData.get(currentIndex).count, or listview.model.get(currentIndex).count
As for the hack that is mentioned by #Teimpz that is also one bad example. When you have more complex requirements and wanting specific elements inside delegate, every delegate has ListView.isCurrentItem property which you can attach and check. This would mean you can add property var myTargetItem to listview, and set it from child to whatever element you want if that delegate is current http://doc.qt.io/qt-5/qml-qtquick-listview.html#isCurrentItem-attached-prop
You can of course do that for any kind of event, maybe activeFocus so you could only reference activeFocused item.
This once again give you ability to expose only wanted elements without any advanced logic or lopping. Combining this with signals you can create very complex but clean interfaces without searching through children items.
So in the end maybe less nice but still better than searching for elements would be to add property int currentItemCount: 0 to listview. In delegate (Row element) you then add property bool isCurrentItem: ListView.isCurrentItem
so you get onIsCurrentItemChanged signal inside delegate, where you can do:
onIsCurrentItemChanged: if(isCurrentItem) listview.currentItemCount = count
so you have your current item count always set
The simple way is using itemAtIndex() like intemAt() in Repeater.
First of all: if you are trying to access list elements from outside your list, this is a good indicator that you should rethink your desing.
Now the solution: a listview has more children than only its items. You can filter them out by defining a property "property string type: "myType" " for example. Then find the items by looping over the children and only take those where the type property equals "myType".
Its somewhat of a hack but again you should really not be doing this in the first place.
myListView.itemAtIndex(currentIndex)).function_name()

How can I get a specific button running on tvOS (AppleTV) to take focus? (Objective C)

The project have some views with different buttons. When I hide a view and show the other view, I can't get the focus on my button.
I think is related to setNeedsFocusUpdate. I have read the Apple doc. There is not any example.
Does anyone know how to do it and put an example (Objective C)?
You need to override preferredFocusedView, and when you are hiding one view and showing there call this method setNeedsFocusUpdate, your preferredFocusedView implementation should be something like this
- (UIView *)preferredFocusedView
{
// Add your logic here, it could be more complicated then what is below
if (view1.hidden)
{
return _button;
}
else
{
return _button2
}
}
And if you want to make custom view get focus, override canBecomeFocused method and return true
Edit
You can use add a breakpoint and execute this command po [buttonYouWantToFocus _whyIsThisViewNotFocusable] it will tell you why its not focusable.
If you are adding a sub view programmatically, maybe this is what you want:
- (UIView *)preferredFocusedView {
return [view1 preferredFocusedView];
}
I realize your question is specific to Objective-C but here is a way to solve for this in Swift. You need to override the preferredFocusedView property.
override var preferredFocusedView: UIView? {
guard primaryView.hidden == false else {
return secondaryView
}
return primaryView
}
Then just call setNeedsFocusUpdate() whenever an event happens that causes your views to be hidden. Hope this helps...
Another option (if you don't want to use preferredFocusedView) is, instead of setting your view to be hidden, simply remove it from it's superview, like so:
myView.removeFromSuperview()
This automatically takes the focus away from the button that is removed and gives it to another one that is still on screen.

Animating UIVisualEffectView Blur Radius?

As the title says it, is there a way to animate a UIVisualEffectView's blur radius? I have a dynamic background behind the view so the ImageEffects addition can't be used... The only thing that can do this as far as I know is to animate the opacity but iOS complains saying that doing that breaks the EffectView so it definitely seems like a bad idea... Any help would be gladly appreciated.
The answer is yes. Here's an example for animating from no blur -> blur:
// When creating your view...
let blurView = UIVisualEffectView()
// Later, when you want to animate...
UIView.animateWithDuration(1.0) { () -> Void in
blurView.effect = UIBlurEffect(style: .Dark)
}
This will animate the blur radius from zero (totally transparent, or rather - no blur effect at all) to the default radius (fully blurred) over the duration of one second. And to do the reverse animation:
UIView.animateWithDuration(1.0) { () -> Void in
blurView.effect = nil
}
The resulting animations transform the blur radius smoothly, even though you're actually adding/removing the blur effect entirely - UIKit just knows what to do behind the scenes.
Note that this wasn't always possible: Until recently (not sure when), a UIVisualEffectView had to be initialized with a UIVisualEffect, and the effect property was read-only. Now, effect is both optional and read/write (though the documentation isn't updated...), and UIVisualEffectView includes an empty initializer, enabling us to perform these animations.
The only restriction is that you cannot manually assign a custom blur radius to a UIVisualEffectView - you can only animate between 'no blur' and 'fully blurred'.
EDIT: In case anybody is interested, I've created a subclass of UIVisualEffectView that gives you full control over blur radius. The caveat is that it uses a private UIKit API, so you probably shouldn't submit apps for review using it. However, it's still interesting and useful for prototypes or internal applications:
https://github.com/collinhundley/APCustomBlurView