How to install OpenCV with QT enabled

I want to install OpenCV with qt enabled. Here is the formula code for it.

For my purpose, it should be: depends_on "qt" and -DWITH_QT=ON

Is there a way I can install it using brew, or should I install it from source?

You can use brew extract to make a copy in a personal repo/tap where you can make edits to the formula.