KLatexFormula seems to do about what you want. Maybe you can use it.

http://klatexformula.sourceforge.net/

If that should be ok with its license maybe you can see how it's done and do something similar yourself. (Is that ok if both your 'inspiration' and your own code are GPL, what if not?)

HTH
Christoph