views:

119

answers:

1

I need to create my own codec, i.e. subclass of QTextCodec. And I'd like to use it via QTextCodec::codecForName("myname");
However, just subclass is not enough. QTextCodec::availableCodecs() does not contain my codec name.

QTextCodec documentation does not cover the area of proper registration of a custom codec:

Creating Your Own Codec Class

Support for new text encodings can be added to Qt by creating QTextCodec subclasses.

The pure virtual functions describe the encoder to the system and the coder is used as required in the different text file formats supported by QTextStream, and under X11, for the locale-specific character input and output.

To add support for another encoding to Qt, make a subclass of QTextCodec and implement the functions listed in the table below.
name()
aliases()
mibEnum()
convertToUnicode()
convertFromUnicode()

You may find it more convenient to make your codec class available as a plugin; see How to Create Qt Plugins for details.

So, I've tried to dig a little into plugins' direction. But I don't want to have a separate project with plugin. Is it possible to declare plugin within the same project?

Or is there a direct way to register my codec into QTextCodec? This is preferable.

+1  A: 

according to qtextcodex.cpp any new codec is added to the collection of registered codecs (*static QList all) by its own constructor. So creating an instance of your codec class should do the trick; code below worked fine for me:

QMyCodec myCodec;

foreach (QByteArray codecName,  QTextCodec::availableCodecs())
{
    QString codecNameStr(codecName);
    qDebug() << codecNameStr;
}

QTextCodec* codec = QTextCodec::codecForName("MyNewCodec");
if (codec)
{
    qDebug() << "found ";
    qDebug() << codec->name() << '\n';
}

QTextCodec::availableCodecs returned:

"MyNewCodec"
"System"
"roman8" "hp-roman8"
"csHPRoman8" ...

QTextCodec::codecForName returned a pointer to my codec class

hope this helps, regards

serge_gubenko
Thanks, you're right! My codec's constructor didn't call inherited QTextCodec's constructor. That is why my codec wasn't registered. I should have taken a look at Qt sources.
Anton