Improve generating toc

Borrow code from PyQt examples;
probably should avoid recursion, hm