OS Edit/Paste Qt Quick.2 TextField 的菜单

OS Edit/Paste menu for Qt Quick.2 TextField

如何通过右键单击所选文本获得 OS 特定的 QtQuick.Controls 2* TextField 粘贴菜单。

有效:

import QtQuick.Controls 1.4

TextField
{
    placeholderText: qsTr("Filter")
    selectByMouse: true
}

然后给我菜单,而

import QtQuick.Controls 2.2

TextField
{
    placeholderText: qsTr("Filter")
    selectByMouse: true
}

这对右键单击没有任何作用。

我使用的是 5.9 LTS 版本,并且坚持使用了一段时间。

它既不能在手动安装了 5.9 的 Ubuntu Linux 16.04 上运行,也不能在 msys2 上的 Windows 10、mingw{32,64} 上运行。

据我在 Qt 错误跟踪器中所见,这是一个缺失的功能 (QTBUG-35598),即使在 Qt 5.10 中也是如此。

我认为恕我直言,这是为了确保应用程序具有一致的外观和感觉,而与平台无关。

恐怕您必须实现自己的上下文菜单。这是我想出的一个片段:

property int selectStart
property int selectEnd
property int curPos

TextField
{
    id: textInput
    placeholderText: qsTr("Filter")
    selectByMouse: true

    MouseArea {
        anchors.fill: parent
        acceptedButtons: Qt.RightButton
        hoverEnabled: true
        onClicked: {
            selectStart = textInput.selectionStart;
            selectEnd = textInput.selectionEnd;
            curPos = textInput.cursorPosition;
            contextMenu.x = mouse.x;
            contextMenu.y = mouse.y;
            contextMenu.open();
            textInput.cursorPosition = curPos;
            textInput.select(selectStart,selectEnd);
        }
        onPressAndHold: {
            if (mouse.source === Qt.MouseEventNotSynthesized) {
                selectStart = textInput.selectionStart;
                selectEnd = textInput.selectionEnd;
                curPos = textInput.cursorPosition;
                contextMenu.x = mouse.x;
                contextMenu.y = mouse.y;
                contextMenu.open();
                textInput.cursorPosition = curPos;
                textInput.select(selectStart,selectEnd);
            }
        }

        Menu {
            id: contextMenu
            MenuItem {
                text: "Cut"
                onTriggered: {
                    textInput.cut()
                }
            }
            MenuItem {
                text: "Copy"
                onTriggered: {
                    textInput.copy()
                }
            }
            MenuItem {
                text: "Paste"
                onTriggered: {
                    textInput.paste()
                }
            }
        }
    }
}

保存和恢复选择的代码来自 KDE plasma(看看here)因为默认情况下,TextField 会在右键单击后重置选择。