Usually the reason the PTO will not stay in gear is because of a loose PTO bearing. This can be caused by a badly worn bearing, a broken snapring groove in the PTO bearing housing or the bearing retainer sleeve having moved from where it should be.
Any movement front to back will cause it to jump out of gear.
The PTO coupling splines can also be worn and cause it to jump out of gear too, but not as often as the before mentioned things.
The detent is another thing to examine but it is less likely to be the problem.
Always be sure that the telescoping portion of the drive shaft is well lubricated or it can damage the PTO bearing etc.