[BR-PT]
This is an relatively advanced grammatical concept if you are beginner, but we can try:
You use QUÊ:
1. When it is an interjection, ie, when express surprise or amazement feeling. Always with ^ and followed by exclamation point:
● Quê! Conseguiu chegar a tempo?
● Quê! Você por aqui?
Note: As interjection, is also used the variation "o quê": O quê! Ela fez isso?!
2. When it is in the end of a sentence, immediately before a point (final, interrogation ou exclamation) or ellipsis:
● Afinal veio aqui fazer o quê? / Você precisa de quê?
● Estamos rindo sem ter de quê.
3. When it is a noun, ie, when it has the meaning of something, anything. Usually is preceed by an article or numeral:
● Sinto um quê de insatisfação.
● Há um quê inexplicável em sua atitude.
If it doesn't match with any of this cases is used QUE.
"O que" is just a variation.