Delimitation of the Q wave is a difficult problem, especially if the SNR is poor. The code shared via physionet as suggested by Shahla is a very good start. You might want to read....
Qinghua Z, Manriquez AI, Medigue C, Papelier Y, Sorine M, (2006) An algorithm for robust and efficient location of t-wave ends in electrocardiograms. IEEE Trans Bio Eng 53:2544–2552.
and
Madeiro JPV, Cortez PC, Marques JAL, Seisdedos CR, Sobrinho CR (2012) An innovative approach of QRS segmentation based on first-derivative, Hilbert and wavelet transforms. Med Eng Phys 4(9):1236–1246.