This decomposition is not unique in the class of all groups, although, as the other answer points out, it is true fir finite groups.
One reason that the result fails in general is that groups are not cancellable in general. A group $H$ is cancellable if the following holds.
$$H\times Q\cong H\times P\Rightarrow P\cong Q$$
Finite groups are cancellable, but in general groups are not (see this question - $\mathbb{Z}$ is a counter-example). If your result held then the decompositions of $P$ and $Q$ would have to be the same, and hence $P$ and $Q$ they would have to be isomorphic, so all groups would be cancellable.
As finite groups are cancellable, this proof only works for general groups and not for finite groups.