How do I code this as a method?
You really can't be serious, are you? Asking how you add a member function to a C++ class? There is no magic here. Just because MainWindow is derived from QMainWindow it is still a C++ class. You can add anything you want to it as either a member variable or method.