Search code examples
latexlistingstabular

LaTeX: vertical alignement in a table containing a listing


In LaTeX, I'm using the listings package to display some code snippet inside a table. But it seems that when using this package, the vertical alignement of the cells is changing.

Here is some code :

\documentclass[a4paper,11pt]{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{lmodern,textcomp}
\usepackage[frenchb]{babel}
\usepackage{listings}

\begin{document}
\begin{tabular}{ll}
\hline Méthode & Exemple d'utilisation\\
\hline isLetter()&
\begin{lstlisting}
QChar MyChar('x');
bool IsLetter = MyChar.isLetter();
// IsLetter vaut vrai
// bla bla bla
\end{lstlisting}\\
\hline
\end{tabular}
\end{document}

and here is what I get (notice the centered vertical alignement of the first column) :

http://img820.imageshack.us/img820/8509/image4l.png.

If I avoid using the listings package inside the table, the vertical alignement is different (centered) :

\begin{tabular}{lp{5cm}}
\hline Méthode & Exemple d'utilisation\\
\hline isLetter()&
QChar MyChar('x');
bool IsLetter = MyChar.isLetter();
// IsLetter vaut vrai
// bla bla bla
\\
\hline
\end{tabular}

http://img691.imageshack.us/img691/8585/image5gy.png.

What I would like is to put some code inside the table but keep the vertical alignement to top for the cells.


Solution

  • Tell latex to align it at the top of the baseline of its textline by the option boxpos.

    \begin{lstlisting}[boxpos=t]
    QChar MyChar('x');
    bool IsLetter = MyChar.isLetter();
    // IsLetter vaut vrai
    // bla bla bla
    \end{lstlisting}
    

    The problem also happens with other boxes

    \parbox[t]{3cm}{Hello\\World\\Peace}
    \parbox[t]{3cm}{Goodbye}
    

    If you leave out the position parameter t, it will align both boxes centered relative to each other.