Saving data from SQLite data base into a Variable - c++

I'm trying to save the username from the database into a variable to use in another QDialog, but the variable is blank when I try to use it in the other dialog
qry.prepare("select nome from Users where email='"+user+"' and senha='"+password+"'");
if(qry.exec()) {
int count=0;
while(qry.next()) {
ui->label_2->setText(qry.value(0).toString());
count++;
}
if (count == 1) {
usuario = ui->label_2->text();
ui->errologin->setText("");
logado= true;
this->hide();
}
This is how i'm trying to call it in the other Dialog:
ui->label->setText(log.usuario);
And this ist the variable declaration in the header file:
public:
explicit login(QWidget *parent = nullptr);
~login();
bool logado;
QString usuario;

There is one thing that you could do better, instead of this:
qry.prepare("select nome from Users where email='"+user+"' and senha='"+password+"'");
Replace it by:
qry.prepare("select nome from users where email=? and senha=?");
qry.bindValue(0, user);
qry.bindValue(1, password);
Please, don't build your queries concatenating strings.
Other than that, there is no way to tell where is your mistake, because you don't provide a minimal reproducible example, as #AlanBirtles and #eyllanesc have requested. I don't see the problem in the code you provided, it may be somewhere hidden in the code that you don't show.
Another advice: trying to reduce your problem to a minimal test program may help you to find the problem by yourself. For instance, if you doubt about your usage of the QSqlQuery class, then put your query in a console program and see if it returns the correct results. If it still doesn't work right, then post your (full) test program here in SO.

Related

not positioned on a valid record

Im New in Qt
I have problem in my app.
This is my code:
voidDialog::on_tableView_activated(constQModelIndex&index)
{
QString valu=ui->tableView->model()->data(index).toString();
QSqlQuery qryview;
qryview.prepare("SELECT* FROM employ where nomper='"+valu+"' or prenomper='"+valu+"'");
ui->lineEdit_2->setText(qryview.value(0).toString());
ui->lineEdit_3->setText(qryview.value(1).toString());
}
I want to recuperate my data in QLineEdit.
When I use SQLite, there is no problem.
But when I use MySQL no result shows in lineEdit.
qsqlquery::value: not positioned on a valid record.
The problem is that you are trying to retrieve the row without initializing it. The right way to do this is by using query.next(), below is the code example:
QString valu=ui->tableView->model()->data(index).toString();
QSqlQuery qryview;
qryview.prepare("SELECT* FROM employ where nomper='"+valu+"' or prenomper='"+valu+"'");
qryview.exec();
while(qryview.next()) {
ui->lineEdit_2->setText(qryview.value(0).toString());
ui->lineEdit_3->setText(qryview.value(1).toString());
}
This should work, if not try to print the lastQueryError and see if query is executed coreectly.

Scout Eclipse check for dirty fields

When you try to close Swing application and you change same value in field, application ask you if you want to save changes.
My first question is why RAP application doesn't ask same question ?
Second and more important question is how to force validation of fields change and how to manipulate this.
for example :
I have table with rows and some fields below table. If I click on row some value is entered in fields. I can change this value and click button save.
I would like to force change validation on row click. So if changes ware applied and if I click on row, application should warn me that some changes are not saved.
But I should be able to manipulate what is change and what is not. For example if table on row click fill some data if fields this is not change, but if I entered value is same fields this is change.
I discovered method
checkSaveNeeded();
But it does nothing. (if I change values or not)
I see that every field has mathod
#Override
public final void checkSaveNeeded() {
if (isInitialized()) {
try {
propertySupport.setPropertyBool(PROP_SAVE_NEEDED, m_touched || execIsSaveNeeded());
}
catch (ProcessingException e) {
SERVICES.getService(IExceptionHandlerService.class).handleException(e);
}
}
}
so I should manipulate changes throw m_touched ?
How is this handled in Scout ?
ADD
I am looking for function that check for dirty fields and pops up message dialog, same as when closing form, and way to set fields dirty or not.
I look here and here, but all it describes is how values is stored for popup messages and dot how to fire this messages (validation).
My first question is why RAP application doesn't ask same question ?
I am not sure to know which message box you mean but it should be the case.
There are several questions about unsaved changes and form lifecycle in the Eclipse Scout Forum. I think you can find them with Google.
I have also taken the time to start to document it in the Eclipse Wiki:
Scout Field > Contribution to unsaved changes
Form lifecycle
I think you should implement execIsSaveNeeded() in the corresponding field. The default implementation in AbstractTableField uses the state of the rows, but you can imagine the logic you want.
#Order(10.0)
public class MyTableField extends AbstractTableField<MyTableField.Table> {
#Override
protected boolean execIsSaveNeeded() throws ProcessingException {
boolean result;
//some logic that computes if the table field contains modification (result = true) or not (result = false)
return result;
}
//...
I hope this helps.
I am looking for function that check for dirty fields and pops up message dialog, same as when closing form.
Are you speaking from this message box that appears when the user clicks on Cancel in the form?
There is no specific function that you can call for that. But you can check the beginning of the AbstractForm.doCancel() function. It is exactly what you are looking for.
I have rewritten it like this:
// ensure all fields have the right save-needed-state
checkSaveNeeded();
// find any fields that needs save
AbstractCollectingFieldVisitor<IFormField> collector = new AbstractCollectingFieldVisitor<IFormField>() {
#Override
public boolean visitField(IFormField field, int level, int fieldIndex) {
if (field instanceof IValueField && field.isSaveNeeded()) {
collect(field);
}
return true;
}
};
SomeTestForm.this.visitFields(collector);
MessageBox.showOkMessage("DEBUG", "You have " + collector.getCollectionCount() + " fields containing a change in your form", null);
I have changed the Visitor to collect all value fields with unchanged changes. But you can stick to the original visitField(..) implementation. You cannot use P_AbstractCollectingFieldVisitor because it is private, but you can have a similar field visitor somewhere else.
I am looking for a way to set fields dirty or not.
As I told you: execIsSaveNeeded() in each field for some custom logic. You can also call touch() / markSaved() on a field to indicate that it contains modifications or not. But unless you cannot do otherwise, I do not think that this is the correct approach for you.

Word automation with C++ Builder 5

I'm trying to control Word through a c++ builder 5 application. I would like to
open a ".dot" model file created with Word and modify it. In the ".dot" model file
there are some fields. For example, Title, LastName, FirstName, Address
and so on, and I would like to modify these fields putting text into them and then
saving file with a new name, for example "Warning.doc" leaving the ".dot" file
unaltered.
I can open the file, count the number of fields it contains, but then
when it comes to replacing each field with a string I don't know how to do because
I don't have a complete documentation on OleFunction and OlePropertyGet methods. I attach my source code to this message, can anybody help me to solve this problem please?
try
{
my_word = Variant::CreateObject("word.application");
}
catch (...)
{
Application->MessageBox("Unable to obtain Word automation object",
"Error:",MB_OK | MB_ICONERROR);
}
my_word.OlePropertySet("Visible", (Variant)true);
void __fastcall TForm1::Button2Click(TObject *Sender)
{
Variant this_doc;
Variant my_fields;
Variant test;
int k,field_count;
AnsiString test1;
AnsiString filename = "d:\\ProgrammaWord\\1-Avviso.dot";
my_docs = my_word.OlePropertyGet("Documents");
this_doc = my_docs.OleFunction("Open", filename);
my_fields = this_doc.OlePropertyGet("Fields");
field_count = my_fields.OlePropertyGet("Count");
for(k = 1; k <= field_count; k++)
{
test = my_fields.OleFunction("Item",(Variant)k);
test1 = test.OleFunction("Value"); //This instruction throws an exception
// "Value" is not a recognized parameter
// in this case
Memo1->Lines->Add(test1);
}
}
I never used word Ole but I used it for Outlook and Excel, I can't try it with word since I'm currently on OSX but you should try something similar as what I did.
The generic way of using Ole was to OleGetproperty() while you get the targeted field then OleSetProperty("action", ...).
for example when I wanted to change the color of the text in a particular cell of my excel document I used:
Variant _excel = Variant::CreateObject("Excel.Application");
Variant _workbook = _excel.OlePropertyGet("WorkBooks").OleFunction("Open", filename);
Variant _worksheet = _workbook.OlePropertyGet("WorkSheets", sheet);
_worksheet.OlePropertyGet("Cells", row, col).OlePropertyGet("Font").OlePropertySet("Color", color);
Here I instanciate an excel object, then I load a file into it (_workbook), then I select the _worksheet from the _workbook and I start my business.
Here comes the interesting part:
It concist of getting to a particular cell, getting the font object from it, and then setting the color of this font object.
Disclaimer: This is an example from my sources for excel, it's not directly related to your example, but maybe you can understand the principe with it. I can't try to figure out what you need because I have no windows right now.
Hope this can help you. Finding ressources for OLE can be fierce if you don't have the good patterns to look for.

Passing values through links in QT

I'm writing a program in C++ and qt4 that is supposed to generate a various number (hundreds )of clickable links in a QTextBrowser depending on data from input files.
The idea is that when the user clicks one of these links a value will be passed to a function named 'on_QTextBrowser_anchorClicked(QUrl)'.
I have created a QTextBrowser which displays HTML code and I manage to create different links to every element added. The problem lies within passing the Url defined in href="URL" to the QUrl.
When setOpenLinks for the QTextBrowser is "true", and I print the URL I get the correct result. But I can't pass this URL (which is a value and not a real URL) to a function.
When setOpenLinks is "false", the anchorClicked(Url) function passes "" as the Url and here I would like to have the URL printed when setOpenLinks=true.
How can I achieve this? Is there a better way (probably is) to connect a various number (approx. between 50-1000) of generated links to a function using QTextBrowser.
My code:
Compassindex.cpp
void CompassIndex::on_seqBrowser_anchorClicked(QUrl input)
{
QString Input = input.toString();
QByteArray nByte = Input.toUtf8();
std::cerr<<Input.data(); //Print Url on the screen to ensure value is passed
}
void CompassIndex::readfile()
{
QString Line;
Int number_out=0;
... //Imports data that will be printed in the QTextBrowser
... //loop for creating links for n number of elements
Line="<a href=\"";
Line+=number_out; //the value (fake Url) that I want to pass to anchorClicked()
Line+="\">";
Line+=nameArr[n]; //inserts the name for the link
Line+="</a>";
number_out++;
...
ui->seqBrowser->insertHtml(Line);
... //end of loop
}
Many thanks for your reply!
I'm using QTextBrowser to provide an actionable user interface for pqConsole. You can read more about in this answer.
I pass around Prolog invocations, and all seems to be working. My anchorClicked slot is as simple as
void ConsoleEdit::anchorClicked(const QUrl &url) {
query_run(url.toString());
}
Note I also have defined (as dummy)
void ConsoleEdit::setSource(const QUrl &name) {
qDebug() << "setSource" << name;
}
I don't touch setOpenLinks(), that defaults to true according to the docs.

C2664 cannot convert parameter 1 from from User *const to User in Qt C++

I am new to C++ and Qt, but I have been playing around with it for a couple of days and I need to come up with a basic prototype of my product by Friday, so there is not much time to convert my 7 years of PHP knowledge into C++ knowledge, as I am sure that it takes a lifetime to master C++. I am getting stuck from time to time in the last couple of days due to non-existing knowledge about the small bits and bytes. At this time I have even no idea what to look for on the Internet.
First of all, I am using Qt as my framework to do a simple GUI network client that can talk to my PHP application. I wanted to create a very simple WebAPI class in this application and have the class "webapi". The scenario is very simple, the user starts the application and the applications checks if the user is logged in or not. If not, then it opens up a login dialog. After entering the information (username / password) into the dialog the user object is filled and the method "authenticate" is called.
The authenticate method then calls the fUser method in the webapi class to make a request to the server holding some information to authenticate the user against the server's database.
In code it looks like this:
Savor.cpp:
user = new User();
while ( user->isLoggedIn() != true )
{
LoginDialog loginWindow;
loginWindow.setModal(true);
int result = loginWindow.exec();
if ( result == QDialog::Accepted )
{
user->authenticate(loginWindow.getUsername(), loginWindow.getPassword());
if ( !user->isLoggedIn() )
{
loginWindow.setUsername(loginWindow.getUsername());
loginWindow.exec();
}
}
else
{
exit(1);//exit with code 1
}
}
User.cpp:
void User::authenticate(QString username, QString password)
{
qDebug() << username;
qDebug() << password;
if ( username != "" && password != "")
{
webapi wapi;
loggedIn = wapi.fUser(this);
}
else
{
loggedIn = false;
}
}
webapi.cpp:
/**
Represents the fUser method on the server,
it wants to get a user object
the user will need to be authenticated with this
then all infos about user are transfered (RSA Keypair etc)
* #brief webapi::fUser
* #param username
* #param password
* #return User
*/
bool webapi::fUser(User baseUser)
{
return true;
}
Now you can clearly see that I am not doing anything at the moment in the webapi::fUser method. In fact, I am not even returning what I would like to return. Instead of a boolean I would like to return a User object, actually the same that I got in the first place through the parameter. However, i get a copy constructor error when I do that. (In my savor.h file I have declared a private attribute as a pointer => User *user;)
So the question is, what am I doing wrong when I call the fUser method? Why can I not simply pass the user object itself to the method ? I have not got around to fully understand const, and pointers and when to use what.
With Qt creator I actually use the MS Visual C++ compiler which throws the error as in the title:
C2664 'webapi::fUser' : cannot convert paramter 1 from 'User *const' to 'User'
I have read http://msdn.microsoft.com/en-us/library/s5b150wd(v=vs.71).aspx this page explaining when this happens, the only solutions is the conversion of the object itself.
If thats the case I might approach the entire problem in the wrong way.
I am looking forward to your tips and help on this matter.
Thank you very much.
webapi::fuser takes a User by value, but you are passing it a User* here:
wapi.fUser(this);
Either pass a User:
wapi.fUser(*this);
or change webapi to take a pointer to User.