Basically, to gain a loyalty level, your pet needs to, no matter what, gain at least 5% of the XP you, the Hunter, needs for your next level. This is required even if your pet is your level (which means they aren't actually gaining the XP). But there's also a time component on every loyalty level past Unruly. For example, to get to level 4 from level 5, you not only need the experience gain, but an hour must pass. This, as Mania says, is why sometimes your pet will ding loyalty while you're standing around in town-- you've gained the experience, but the time has to pass as well.
She's not done yet-- she needs (or someone with some time on their hands could do it as well-- Mania's going through a move lately) to check out if the experience stays the same all the way to 70, or if it increases at the higher levels. She also didn't try this keeping the pet anything other than happy, so the numbers may change if the pet isn't at full happiness. And she didn't explore, at all, what happens when the pet loses loyalty-- if your pet has dropped a level of loyalty, it may be a completely different formula to regain it.
But great work so far, and this is more than enough to give any Hunter a clear idea of how loyalty works in most cases.