Getting text from the lineEdit

Aug 14, 2014 at 6:28pm

I'm sorry for the, I think, most stuoid question ever asked, but how can I get the text from lineEdit in Qt and put it into a variable? This doesn't seem to work:
1
2
string s;
  s= lineEdit->text();

and, how can I get the nmber of a char in a string?
By the way, I'm using QtCreator 5.3.
Last edited on Aug 14, 2014 at 6:29pm
Aug 14, 2014 at 7:32pm
I assume you have ui files so try s = ui->lineEdit->text();.

I am not sure what you are asking for the second question? Do you want the ASCII value, the index, or something else?
Aug 15, 2014 at 3:52pm
I've tried with ui also, but it didn't work. When I do like this
it's writing me: "no match for 'operator=' (opernad tyoes 'std::string{aka::std::basic_string<char>}' and {'QString'}
I mean , if we foe example have a string "abcdefg" and I want to know the index number(sory, I'm not an english native-speaker); For example for a it will be 0, for b it will be 1 for c 2 etc.
Last edited on Aug 15, 2014 at 5:28pm
Aug 15, 2014 at 7:26pm
Without seeing your code I can only guess you are not including string(or Qstring). It is usually better to use Qstring, along with all the other Qt types, over the C++ types.

To get the index number, one way would be to use a for loop.
1
2
3
4
5
for(int i = 0; i < s.length(); ++i)
{
     if(s[i] == 'b')
         int index = i;
}

Depending on how you plan to use it, there is likely to be a better way though. The docs are the best place to look to find what will work best for your purposes: http://qt-project.org/doc/qt-5/qstring.html
Aug 15, 2014 at 8:40pm
Oh! Thank you so much! But what about getting text from lineEdit? I still didnt find a solution....((
Last edited on Aug 15, 2014 at 9:00pm
Aug 15, 2014 at 10:47pm
Those are the two ways to do it, if neither is working then you have something wrong somewhere else in your code. The following code works fine with a window containing a QLineEdit, QPushButton, and a QLabel. When you click the button, the text from the QLineEdit gets assigned to the string str and displayed in the QLabel. It is the only thing I added besides the widgets.
1
2
3
4
5
void MainWindow::on_pushButton_clicked()
{
    QString str = ui->lineEdit->text();
    ui->label->setText(str);
}

Without seeing your code I cannot say more.
Aug 16, 2014 at 4:15am
Oh< Thank you!
Topic archived. No new replies allowed.