How to add text to selected note (MS3.3)

• Nov 6, 2019 - 09:54

First way to add text is

var cursor = curScore.newCursor();
cursor.rewind(Cursor.SELECTION_START);
console.log('Segment:', cursor.segment)
console.log('Selection:', curScore.selection)
var text = newElement(Element.STAFF_TEXT);
text.text = 'test1';
cursor.add(text);

But it works only for range selection. And nothing changed if only one note is selected (cursor.segment is null).

New for MS3.3 is curScore.selection. Next way:

var selectedElementsArray = curScore.selection.elements;
if (selectedElementsArray.length > 0){
var elem = selectedElementsArray[0];
var root = elem.parent;
console.log(root.name, root.add);
var text = newElement(Element.STAFF_TEXT);
text.text = 'test1';      
root.add(text);
}

But this code crushes MuseScore.


Comments

What is root?

If you started from a notehead, then root will be the Chord/ChordRest element, not the Segment. Try travelling up the parent chain until the elementType is a Segment

In reply to by Pobezhimov Serge

Nevertheless a Text element isn't attached to a Chord afaik, so making a Chord its parent seems to be the error (and is likely causing it)

You could still go upwards to the segment, then create a Cursor and forward it to the correct segment and perform the add via the Cursor

I've found some way to solve problem, but it may be simplified?

cursor.rewind(0)
And then iterate over cursor.next() and comparing cursor.tick with element.parent.parent.tick (Segment)

Do you still have an unanswered question? Please log in first to post your question.