Sexually dimorphic abdominal pigmentation and segment morphology evolved recently in the melanogaster species group of the fruitfly Drosophila. Here we show that these traits are controlled by the bric à brac [corrected] (bab) gene, which integrates regulatory inputs from the homeotic and sex-determination pathways. bab expression is modulated segment- and sex-specifically in sexually dimorphic species, but is uniform in sexually monomorphic species. We suggest that bab has an ancestral homeotic function, and that regulatory changes at the bab locus played a key role in the evolution of sexual dimorphism. Pigmentation patterns specified by bab affect mating preferences, suggesting that sexual selection has contributed to the evolution of bab regulation.