When a capacitor is disconnected from the battery, its charge ($Q$) remains constant. When it remains connected, its voltage ($V$) remains constant. The work done to change the configuration (e.g., remove a dielectric) is the change in the stored potential energy, $W = \Delta U = U_{final} - U_{initial}$.