There is no such function
Assumption on the Function space
I assume that $f$ has to be a polynomial in the variables $X$ and $Q$, i.e., $f$ is a sum of terms of the form
$$
a_k X^{k_1} Q^{k_2} X^{k_3} \dots Q^{k_j}
$$
where $a_k$ is a real/complex number.
$$
f(X,Q) = \sum_{i=0}^\infty \sum_{\substack{k \text{ is an integer} \\\\ \text{partition of } i}} a_{k} X^{k_1} Q^{k_2} X^{k_3} \dots Q^{k_j}
$$
If this is not the class of functions you had in mind, could you specify further?
The proof
As there are no restrictions on $X$ and $Q$ the zero matrices are possible choices for $X$ and $Q$ (choose $q$ to be the zero vector for $Q$).
Then all terms of $f$ which involve at least one $X$ or $Q$ are 0.
$$
f(0,0) = a_0 X^0 Q^0 = a_0 \mathbb{I}
$$
with the identity matrix $\mathbb{I}$.
Thus except for the case of $n=2$, $a_0 \neq 0$ the matrix $f(0,0)$ never has rank 2, however in this case $f(0,0)$ does not have trace $0$.
Alternatives
There are several ways to modify the assumptions to get this to work:
- Restrict the set of matrices $X$ and $Q$ for which the requirements have to hold. Especially, exclude the zero matrices.
- Extend the set of possible functions, to, for example, include the constant function $f(X,Q) = \operatorname{diag}(1, -1, 0, \dots, 0)$.
- Drop one of the requirements.