[Qt-interest] How to change std::vector<char> to QString?

Tim Dewhirst tim at bugless.co.uk
Mon Dec 14 10:12:25 CET 2009


Hi Longchao,

donglongchao wrote:
> Help!I am using a shared library in which there is a function who return 
> a std::vector<char>.I want to assign it to a QString object to show it 
> on my GUI.But I do not know how to do it.Is there any constructor/member 
> function in QString to do this?Or is there any constructor/member 
> function in std::vector<char> to change itself into a char* or sth like 
> that so that I can use it as a parameter in QString's constructor/member 
> function to do this?I search the document but find nothing.If there is 
> no,do I have to pull each element of the std::vector<char> out and then 
> push them into my QString to do this?While I do not like this method 
> very much.:-(.So,please point me the right direction and a better 
> approach.Thanks a lot in advance.

You can do this:

#include <vector>
#include <cstring>

#include <QString>
#include <QDebug>

int main( int argc, char* argv[] )
{
     std::vector< char > input( 10, 0 );
     strcpy( &input[0], "hello" );

     // use the appropriate from* method according to data in vector
     QString output = QString::fromLatin1( &input[0] );
     qDebug() << output;

     return 0;
}

Thanks,

Tim



More information about the Qt-interest-old mailing list