We analyse the evolution of the oxygen abundance gradient of star-forming galaxies with stellar mass M * ≥ 10 9 M in the simulation over the redshift range 𝑧 = [0, 2.5]. We find that the median metallicity gradient of the simulated galaxies is close to zero at all 𝑧, whereas the scatter around the median increases with 𝑧. The metallicity gradients of individual galaxies can evolve from strong to weak and vice-versa, since mostly low-metallicity gas accretes onto the galaxy, resulting in enhanced star formation and ejection of metal enriched gas by energy feedback. Such episodes of enhanced accretion, mainly dominated by major mergers, are more common at higher 𝑧, and hence contribute to increasing the diversity of gradients. For galaxies with negative metallicity gradients, we find a redshift evolution of ∼ −0.03 dex kpc −1 /𝛿z. A positive mass dependence is found at 𝑧 ≤ 0.5, which becomes slightly stronger for higher redshifts and, mainly, for M * < 10 9.5 M . Only galaxies with negative metallicity gradients define a correlation with galaxy size, consistent with an inside-out formation scenario. Our findings suggest that major mergers and/or significant gas accretion can drive strong negative or positive metallicity gradients. The first ones are preferentially associated with disc-dominated galaxies, and the second ones with dispersion-dominated systems. The comparison with forthcoming observations at high redshift will allow a better understanding of the potential role of metallicity gradients as a chemical probe of galaxy formation.