Quê is generally used:
(1) At the end of a sentence/clause, whether or not it’s an interrogative one. You can’t end a sentence with que, so the choice is easy in these cases.
It can also appear in other parts of a sentence, but that’s pretty much limited to these two cases:
(2) Sentences/clauses without a verb or with a verb used in the infinitive form and impersonally
(3) Sentences/clauses where it’s used as a noun
(1) Não tens de quê! (You’re welcome!)
(1) Disseste o quê? (You said what?)
(2) Para quê tanto drama? (Why so much drama?) - verbless sentence
(2) Para quê esperar? (Why wait?) - impersonal sentence
(3) Isto tem o seu quê de loucura. (This has a bit of madness to it)
(3) Aquilo ganhou um quê de intensidade. (That gained a touch of intensity)
And you know what? Quê is the exception. Memorize the few situations where quê is used and you already know that, in every other case, the choice can probably be reduced to que or o que.
Now, when it comes to que, I think it’s easier to consider que as the baseline and then look at situations where the preceding O is a) optional, b) mandatory or c) not recommended or even forbidden.
a) o before que is optional:
- At the start of an interrogative sentence/clause where que is used in the sense of what and is not followed by any noun. If you can mentally replace que with que coisa in an interrogative sentence, you should also be able to use o optionally.
Que se passa? = O que se passa? = Que (coisa) se passa? (What’s happening?)
Que é que fizeste? = O que é que fizeste? = Que (coisa) é que fizeste? (What did you do?)
b) o before que is mandatory:
- When o is used as a demonstrative pronoun. If you can mentally replace o with aquilo (a more recognizable demonstrative pronoun), it can’t be removed from the sentence.
- Eu tenho o que tu precisas = Eu tenho (aquilo) que tu precisas. (I have what you need)
- Ela pode fazer o que ela quiser. = Ela pode fazer (aquilo) que ela quiser. (She can do what she wants)
c) o before que is not recommended:
- When none of the above apply! Que can be used in so many different ways on its own that this list would be endless if we tried to cover each case.
Here are some examples:
- Que é que fizeste? (What did you do?) - only the first “Que” can be optionally replaced by “O que”.
Que coisa é essa? (What thing is that?) - Here, because que is immediately followed by a noun, there should be no o before it. Your only other option would be to flip the sentence -> Que é essa coisa? = O que é essa coisa? (What is that thing?)
- O carro que nós comprámos é bonito. (The car we bought is beautiful)
- Mesmo que eu tivesse o tempo, não teria a energia. (Even if I had the time, I wouldn’t have the energy)
There is probably more to be said, but I think this covers just enough. This was a tough question to answer, hah! Hope it makes things a bit clearer for you.