Fix #1797, with awareness of widget visibility.

This fix takes the place of #1801, and fixes #1797.