[Tex/LaTex] Error using \widthof inside tikzpicture

calculationstikz-pgf

\documentclass{article}

\usepackage{tikz}
\usepackage{calc}

\begin{document}

\begin{tikzpicture}
    \newlength{\TextWidth}
    \setlength{\TextWidth}{\widthof{Text}}
    %\node[draw,text width=\widthof{Text}}]{Text}; % this does not work
    \node[draw,text width=\TextWidth]{Text}; % this works
\end{tikzpicture}

\end{document}

With the code above I am getting the following error:

! Undefined control sequence.
\pgfmath@dimen@ …men@@ #1=0.0pt\relax \pgfmath@

l.9 \node[draw,text width=\widthof{Text}]{
Text}

But I am not understanding why, since this code was previously working. I am using TeXLive 2015.

Best Answer

In a tikzpicture, the current font is \nullfont (see pp.124-125, pgfmanual), So \widthof can't work.

You may use the width function provided by TikZ math engine:

\documentclass{article}

\usepackage{tikz}
\usepackage{calc}

\begin{document}


\begin{tikzpicture}
  \node[draw,text width=width("Text")]{Text and text};
\end{tikzpicture}

\end{document}

enter image description here