qvariant_cast causing segfault - qt5

Within qt's item/view framework, I'm trying to save a QColorDialog as user data and then retrieve that dialog as the editor, as well as during paint, in a tableview.
In my class constructor I do
QStandardItem *item = new QStandardItem();
QColorDialog *colorDlg = new QColorDialog(QColor(0,0,255), this);
item->setData(QVariant::fromValue(colorDlg), ColorDialogRole);
mTableModel->setItem(0,2,item);
then, inside my delegate's paint function I have
void ReportFigureTableDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
QVariant vColorDlg= index.data(ReportFigure::ColorDialogRole);
if(vColorDlg.isValid())
{
////////////////////////////////////////////////
// Program segfaults on the next line ... why?
////////////////////////////////////////////////
QColorDialog *colorDlg = qvariant_cast<QColorDialog*>(vColorDlg);
if(colorDlg != NULL)
{
painter->save();
QStyleOptionViewItem opt = option;
initStyleOption(&opt, index);
painter->fillRect(opt.rect, colorDlg->selectedColor());
painter->restore();
}
else
QStyledItemDelegate::paint(painter, option, index);
}
else
QStyledItemDelegate::paint(painter, option, index);
}
During runtime, the table shows up the first time (although with the wrong color ... different issue I assume). I double click to edit the cell and it brings up the dialog as expected. When I close, though, it segfaults on the indicated line. I don't understand why since I think I'm doing all the necessary checks.

You set the data on a QStandardItem object. Meanwhile you are retrieving the data on a QModelIndex object. Now why is the variant valid is a mystery. Maybe because ReportFigure::ColorDialogRole is equal to a build-in Qt role while it should be at least Qt::UserRole.
Anyway In the paint() method you can access the previously set item using
QStandardItem *item = mTableModel->itemFromIndex(index);

Related

Databinding is initialized in improper order by automatically generated executeBindings

Preface
I have a simple app with a viewmodel, a custom UI control, and a TextView. Databinding is setup like this:
LiveData -> control.value -> control.preValue -> TextView
When LiveData is changed, databinding notifies control.value of the new value. control.value setter has a line which also gives the new value to control.preValue. Both properties have calls to their respective databinding listeners to notify databinding that the values have changed and that the UI should be updated. The text value of TextView is bound to control.preValue, so when the listener is notified, the TextView is updated.
This works well at runtime, however there is a problem at initialization.
The Problem
When the UI is first constructed, the LiveData value is not correctly propagated to the TextView. This is because the listeners have not yet been created by the android databinding library, so when control.preValue is set by control.value's setter, the listener is still null.
Diving deeper into executeBindings we can see the cause of the problem.
executeBindings is a function which is part of the *BindingImpl file automatically generated by the databinding library based on the Binding Adapters I have defined. It is responsible for initializing databinding, e.g. creating listeners, registering livedatas, and setting initial values to the UI.
executeBindings starts like this. It initializes variables for all the databound values.
#Override
protected void executeBindings() {
long dirtyFlags = 0;
synchronized(this) {
dirtyFlags = mDirtyFlags;
mDirtyFlags = 0;
}
java.lang.Integer viewmodelBpmGetValue = null;
androidx.lifecycle.MutableLiveData<java.lang.Integer> viewmodelBpm = null;
int bpmPickerPreValue = 0;
androidx.lifecycle.MutableLiveData<java.lang.Boolean> viewmodelPlaying = null;
java.lang.String integerToStringBpmPickerPreValue = null;
int androidxDatabindingViewDataBindingSafeUnboxViewmodelBpmGetValue = 0;
com.okos.metronome.MetViewModel viewmodel = mViewmodel;
Next, it gets the value of control.preValue property and stores it in the earlier created variable. This is already the core of the problem. At this point control.preValue is still at the default value that is defined in the control's definition class, not the LiveData value which will be assigned to it a bit later.
if ((dirtyFlags & 0x18L) != 0) {
// read bpmPicker.preValue
bpmPickerPreValue = bpmPicker.getPreValue();
// read Integer.toString(bpmPicker.preValue)
integerToStringBpmPickerPreValue = java.lang.Integer.toString(bpmPickerPreValue);
}
Next we get the LiveData value from the viewmodel and register it with databinding
if ((dirtyFlags & 0x15L) != 0) {
if (viewmodel != null) {
// read viewmodel.bpm
viewmodelBpm = viewmodel.getBpm();
}
updateLiveDataRegistration(0, viewmodelBpm);
if (viewmodelBpm != null) {
// read viewmodel.bpm.getValue()
viewmodelBpmGetValue = viewmodelBpm.getValue();
}
// read androidx.databinding.ViewDataBinding.safeUnbox(viewmodel.bpm.getValue())
androidxDatabindingViewDataBindingSafeUnboxViewmodelBpmGetValue = androidx.databinding.ViewDataBinding.safeUnbox(viewmodelBpmGetValue);
}
Here it sets control.value to the value of the LiveData in the first if block. This line will trigger the control.value setter, which will set control.preValue, and those setters will both try to call their respective onChange listeners but they will be null because executeBindings hasn't created them yet. They are created in the 2nd if block.
if ((dirtyFlags & 0x15L) != 0) {
// api target 1
this.bpmPicker.setValue(androidxDatabindingViewDataBindingSafeUnboxViewmodelBpmGetValue);
}
if ((dirtyFlags & 0x10L) != 0) {
// api target 1
com.okos.metronome.view.DialPickerBindingAdapter.setPreValueListener(this.bpmPicker, (com.okos.metronome.view.PrePickerBase.OnValueChangeListener)null, bpmPickerpreValueAttrChanged);
com.okos.metronome.view.DialPickerBindingAdapter.setValueListener(this.bpmPicker, (com.okos.metronome.view.PrePickerBase.OnValueChangeListener)null, bpmPickervalueAttrChanged);
}
Finally, the value of the TextView is set, but it is set to the original value of preValue which we cached in a variable in the very first if block. **Not the new value which has been updated to preValue from the LiveData since then.
if ((dirtyFlags & 0x18L) != 0) {
// api target 1
androidx.databinding.adapters.TextViewBindingAdapter.setText(this.tvBpmDisplay, integerToStringBpmPickerPreValue);
}
This seems like an oversight in the databinding library, and I wonder if anyone has any ideas of getting around this? The fix seems pretty simple to just move the first if block in executeBindings down so integerToStringBpmPickerPreValue is set after the value has been set from LiveData, but because executeBindings is automatically generated, I can't do that. There are some ways of changing the order of execution in executeBindings, like which order the bindings are defined in the xaml, but none of that affects the parts I want to change.

QObject::findChildren() for QML object finding

I have an QML form with QQuickApplicationWindow. I need to get QQuickItem pointers on BaseKey elements of QtVirtualKeyboard (it's implementation is placed in separate QML file and loads with Loader of layout when program executes), but it has dynamical (runtime) type like this BaseKey_QMLTYPE_XX, where "XX" is a changeable number.
I found QObject::findChildren() function http://doc.qt.io/qt-4.8/qobject.html#findChild, but i cant find out number "XX" in typename.
How can i find QQuickItem pointer on BaseKey from C++ code?
BaseKey_QMLTYPE_XX looks like what you'd get if you printed the object (print(myObject)). I think that comes from QMetaObject::className().
If the object doesn't have an objectName set, you won't be able to find it using findChild() (unless you have access to the C++ type and there's only one object of that type).
I have a hacky test helper function that does something similar to what you're after:
QObject *TestHelper::findPopupFromTypeName(const QString &typeName) const
{
QObject *popup = nullptr;
foreach (QQuickItem *child, overlay->childItems()) {
if (QString::fromLatin1(child->metaObject()->className()) == "QQuickPopupItem") {
if (QString::fromLatin1(child->parent()->metaObject()->className()).contains(typeName)) {
popup = child->parent();
break;
}
}
}
return popup;
}
You could adapt this to iterate over the children of an object that you pass in. There are a couple more changes than that to get it to work, but the general idea is there.

Why am I getting an EXEC_BAD_ACCESS when setting the info pointer of a FSFileOperationClientContext?

I am using FSCopyObjectAsync to copy files in a Cocoa app. Problem is, whenever I try to set the info field (an object of type void *) the application crashes because of an EXEC_BAD_ACCESS. I'm not sure what I'm doing wrong.
Here's my code:
// Start the async copy.
FSFileOperationClientContext *clientContext = NULL;
if (spinner != nil) {
clientContext->info = (__bridge void *)(spinner); // <- Problem here!
}
status = FSCopyObjectAsync(fileOp,
&source,
&destination, // Full path to destination dir.
CFSTR("boot.iso"), // Copy with the name boot.iso.
kFSFileOperationDefaultOptions,
copyStatusCallback,
0.5, // How often to fire our callback.
clientContext); // The progress bar that we want to use to update.
CFRelease(fileOp);
I'm using ARC, and it works if I comment out the lines dealing with clientContext and pass NULL in the last argument of FSCopyObjectAsync, but that severely cripples my application's functionality. It's definitely the assignment, therefore, that's causing the problem.
You are creating a NULL pointer without allocating it and then trying to reference it. Change the code so you allocate it on stack and pass its address like below.
// Start the async copy.
FSFileOperationClientContext clientContext;
if (spinner != nil) {
clientContext.info = (__bridge void *)(spinner);
}
status = FSCopyObjectAsync(fileOp,
&source,
&destination, // Full path to destination dir.
CFSTR("boot.iso"), // Copy with the name boot.iso.
kFSFileOperationDefaultOptions,
copyStatusCallback,
0.5, // How often to fire our callback.
&clientContext); // The progress bar that we want to use to update.
CFRelease(fileOp);

Getting the code of released key

I'm trying to make a simple platformer using action script 2.0 but I have a problem with getting input from keyboard. I have two function "myKeyDown" and "myKeyUp" that get called whenever a key is pressed down/released.
keyListener.onKeyDown = function(){
myKeyDown();
}
keyListener.onKeyUp = function(){
myKeyUp();
}
The functions check which key was pressed by using Key.getCode() method. It works for myKeyDown but it's buggy for myKeyUp. The bug happens if (for example) I first press A (to move left), then W (to jump), then release W and then release A. The player won't stop moving (even though that's what should happen when you release A)
I understand the problem here. Key.getcode return the code of the last pressed key and what I want is the code for the last released key. I've been searching for hours for a function like this but I haven't found anything.
Here's the code for both myKeyDown and myKeyUp functions
function myKeyDown(){
//A
if(Key.getCode() == 65){
velX=-3;
}else
//D
if(Key.getCode() == 68){
velX=3;
}else
//W
if(Key.getCode() == 87){
if(isInAir == false){
jump();
}
}
}
function myKeyUp(){
//A
if(Key.getCode() == 65){
if(velX==-3){
velX=0;
}
}else
//D
if(Key.getCode() == 68){
if(velX==3){
velX=0;
}
}
}
for cases like this, when you need to hold/release multiple keys a little bit different approach would be better for key handling.
what you can do is use onEnterFrame event listener to check for the pressed keys in case of events when something has to be continuous.
an example
var my_keys:Array = new Array();
my_keys["jump"]=false;
my_keys["right"]=false;
my_keys["left"]=false;
//keydown sets the variables to true
keyListener.onKeyDown = function(){
code=Key.getCode();
if(code==65){
my_keys["left"]=true;
}
if(code==68){
my_keys["right"]=true;
}
if(code==87){
my_keys["jump"]=true;
}
//etc, etc, anything else you wish
//of course, this doesn't prevent you from calling additional one-time events from the keydown!
}
//keyup unsets the button variables
keyListener.onKeyUp = function(){
code=Key.getCode();
if(code==65){
my_keys["left"]=false;
}
if(code==68){
my_keys["right"]=false;
}
if(code==87){
my_keys["jump"]=false;
}
}
now at every point of your game you have a set of keys that are pressed stored in the my_keys array. of course you could use a more generic function inside the keyDown/keyUp and pass the Key.getCode itself directly into the array as indexes instead of the captioned array (like my_keys[Key.getCode()]=true;), it would be even shorter to write. however, i found this to be more illustrative as an example, feel free to modify the code as you need
what you want now is a function that would handle the behavior based on what keys are pressed.
in your case this could, for example, be:
this.onEnterFrame=function(){ //you don't have to use "this" movieclip reference if you have other enterframe events in the movieclip. just don't forget to modify the objcet paths
if(my_keys["left"]){
velX=-3;
}
if(my_keys["right"]){
velX=+3;
}
if((my_keys["jump"])&&(!isInAir)){ //note that i added !isInAir instead of (isInAir==false). this is an equivalent expression, it's just shorter and nicer
jump();
}
}

Controller selection

In my title screen, i have a code saying that the first controller using A is the PlayerIndex.one.
Here is the code:
public override void HandleInput(InputState input)
{
for (int anyPlayer = 0; anyPlayer <4; anyPlayer++)
{
if (GamePad.GetState((PlayerIndex)anyPlayer).Buttons.A == ButtonState.Pressed)
{
FirstPlayer = (PlayerIndex)anyPlayer;
this.ExitScreen();
AddScreen(new Background());
}
}
}
My question is: How can i use the "FirstPlayer" in other classes? (without this, there is no interest in this code)
I tried the Get Set thing but i can't make it work. Does i need to put my code in another class? Do you use other code to make this?
Thanks.
You can make a static variable say : SelectedPlayer,
and assign first player to it!
then you can call the first player through this class,
for example
class GameManager
{
public static PlayerIndex SelectedPlayer{get;set;}
..
..
..
}
and right after the loop in your code, you can say:
GameManager.SelectedPlayer = FirstPlayer;
I hope this helps, if your code cold be clearer that would be easier to help :)
Ok, so to do this properly you're going to have to redesign a little.
First off, you should be checking for a new gamepad input (i.e. you should be exiting the screen only when 'A' has been newly pressed). To do this you should be storing previous and current gamepad states:
private GamePadState currentGamePadState;
private GamePadState lastGamePadState;
// in your constructor
currentGamePadState = new GamePadState();
lastGamePadState = new GamePadState();
// in your update
lastGamePadState = currentGamePadState;
currentGamePadState = GamePad.GetState(PlayerIndex.One);
Really what you need to do is modify your class that deals with input. The basic functionality from your HandleInput function should be moved into your input class. Input should have a collection of functions that test for new/current input. For example, for the case you posted:
public Bool IsNewButtonPress(Buttons buton)
{
return (currentGamePadState.IsButtonDown(button) && lastGamePadState.IsButtonUp(button));
}
Then you can write:
public override void HandleInput(InputState input)
{
if (input.IsNewButtonPress(Buttons.A)
{
this.ExitScreen();
AddScreen(new Background());
}
}
Note: this will only work for one controller. To extend the implementation, you'll need to do something like this:
private GamePadState[] currentGamePadStates;
private GamePadState[] lastGamePadStates;
// in your constructor
currentGamePadStates = new GamePadState[4];
currentGamePadStates[0] = new GamePadState(PlayerIndex.One);
currentGamePadStates[1] = new GamePadController(PlayerIndex.Two);
// etc.
lastGamePadStates[0] = new GamePadState(PlayerIndex.One);
// etc.
// in your update
foreach (GamePadState s in currentGamePadStates)
{
// update all of this as before...
}
// etc.
Now, you want to test every controller for input, so you'll need to generalise by writing a function that returns a Bool after checking each GamePadState in the arrays for a button press.
Check out the MSDN Game State Management Sample for a well developed implementation. I can't remember if it supports multiple controllers, but the structure is clear and can easily be adapted if not.