I'm a complete beginner in Blackberry 10 development. I'm developing an app that should take user input from a text box and search if there is an occurrence of the word in a text file. I'm using the triggered() signal of ActionItem to invoke the search. However, when I try to fetch the user input from within the slot it always returns an empty string ''. What mistake I'm I making.
Thank you in advance.
Here is the code:
main.qml
TextField {
objectName: "anagram"
hintText: "Enter anagram to search"
verticalAlignment: VerticalAlignment.Center
horizontalAlignment: HorizontalAlignment.Center
input {
submitKey: SubmitKey.Done
}
}
application.cpp
ActionItem *main = root->findChild<ActionItem*>("search");
bool res1 = QObject::connect(main, SIGNAL(triggered()), this, SLOT(onSearch()));
void ApplicationUI::onSearch()
{
qDebug() << "slot activated";
QmlDocument *qml = QmlDocument::create("asset:///main.qml").parent(this);
AbstractPane *root = qml->createRootObject<AbstractPane>();
Application::instance()->setScene(root);
TextField* query = root->findChild<TextField*>("anagram");
//THE STRING BELOW ALWAYS RETURNS ''
QString search = query->text();
...
When the slot onSearch
is invoked you are effectively creating an additional UI, unrelated to the one that actually emitted the signal.
Since there's no default setting for the text property of anagram
, what you have concluded is correct; it will always yield an empty string since the field will always be freshly created.
You will need to use the root
associated with the current UI (that the user has inputted data to), instead of creating a new one.
Assuming that you have declared root
as a data-member of ApplicationUI, the below would do what you'd expect (and want).
void ApplicationUI::onSearch()
{
qDebug() << "slot activated";
TextField* query = root->findChild<TextField*>("anagram");
QString search = query->text();
// ...
}
Alternative solution
You could also access the current loaded scene (the equivalent of root
in your snippet) by calling scene()
on the pointer-to AbstractPane
returned by Application::instance ()
:
AbstractPane * current_scene = Application::instance ()->scene ();
QString search = current_scene->findChild<TextField*> ("anagram")->text ();