The following is a translation of part of Rambam's Law of Kings Chapter 1 Halacha 7.
Yet all those who who lack the fear of heaven, even though he possesses much wisdom we do not appoint him to any appointed leadership position in Israel.
Once David was anointed king, he acquired the crown of kingship. Afterwards, the kingship belonged to him and to his male descendents forever, as it is stated (II Shmuel/Samuel 7: 16): 'Your throne shall be established forever.' Nevertheless, his acquisition of the monarchy was conditional, applying only to the spiritually fit among his descendents, as it is stated (Tehillim/Psalms 132:12): 'If your children will keep My covenant'.