In the early Universe, while galaxies were still forming, black holes as massive as a billion solar masses powered quasars. Supermassive black holes are found at the centres of most galaxies today, where their masses are related to the velocity dispersions of stars in their host galaxies and hence to the mass of the central bulge of the galaxy. This suggests a link between the growth of the black holes and their host galaxies, which has indeed been assumed for a number of years. But the origin of the observed relation between black hole mass and stellar velocity dispersion, and its connection with the evolution of galaxies, have remained unclear. Here we report simulations that simultaneously follow star formation and the growth of black holes during galaxy-galaxy collisions. We find that, in addition to generating a burst of star formation, a merger leads to strong inflows that feed gas to the supermassive black hole and thereby power the quasar. The energy released by the quasar expels enough gas to quench both star formation and further black hole growth. This determines the lifetime of the quasar phase (approaching 100million years) and explains the relationship between the black hole mass and the stellar velocity dispersion.