4

I've spend a couple of days trying to understand how the pgfkeys work. As an example, I'd like to read a key's value and then use it to set another key.

In this case, I want to set a node's label to the same content as its text:

% attempt 1
\pgfkeys{/tikz/labeltext/.style={label=\pgfkeysvalueof{/tikz/node contents}}}

% attempt 2
\pgfkeys{/tikz/node contents/.store in=\nc}
\pgfkeys{/tikz/labeltext/.style={label=\nc}}

% attempt 3
\pgfkeys{/tikz/labeltext/.code={\pgfkeyssetvalue{\pgfkeysvalueof{/tikz/node contents}}}}

\begin{tikzpicture}

    \node [labeltext] {test};

\end{tikzpicture}

What I expect to get is

Desired result

but nothing happens.

4

The normal content of a node can't be retrieve from a key. The special node contents key uses some code to store its argument in \tikz@node@content macro (line 896 of tikz.code.tex file).

You may use:

\documentclass[tikz]{standalone}
\makeatletter
\tikzset{
  labeltext/.code={\tikzset{label/.expand once=\tikz@node@content}},
}
\makeatother
\begin{document}
\begin{tikzpicture}
  \node[node contents=test,labeltext];
\end{tikzpicture}
\end{document}

But a simpler solution is:

\documentclass[tikz]{standalone}
\tikzset{
  labeltext/.style={node contents={#1},label={#1}},
}
\begin{document}
\begin{tikzpicture}
  \node[labeltext=test];
\end{tikzpicture}
\end{document}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.