首页 > 解决方案 > 如何获取文件名并将其放入 TextEdit

问题描述

在我的示例中,我有一个文本编辑和一个按钮。我可以使用文件对话框获取文件。我不知道如何将文件名或文件路径放入文本编辑中,我尝试使用substring但效果不佳,我该怎么做?

这是我的代码:

import QtQuick.Dialogs 1.0
import QtQuick.Controls 2.2
import QtQuick 2.6

// This is rectangle parent
Rectangle {
    id: overlay
    width: parent.width
    height: parent.height
    color: "#000000"

   // EditText into Rectangle
   // rec edit tex
   Rectangle{
        id:rectextbox
        width: 150
        height: 22
        anchors.top: recmidle.top
        anchors.topMargin: 39
        anchors.left: recmidle.left
        anchors.leftMargin: 24
        TextEdit{
            id: txtedit
            width: rectextbox.width
            height: rectextbox.height
            anchors.verticalCenter: rectextbox.verticalCenter
            anchors.horizontalCenter: rectextbox.horizontalCenter
        }
    }

        // Using FileDialog to get file
        FileDialog {
        id: file
        title: "Choose an image"
    }

    // Button to find and search file
    Button{
        id: btnput
        width: 50
        height: 22
        background: Rectangle{
            id: btnrtg1
            color: "#737373"
        }
        anchors.top: recmidle.top
        anchors.topMargin: 39
        anchors.right: recmidle.right
        anchors.rightMargin: 76
        Text {
            id: textname1
            anchors.verticalCenter: recbutton1.verticalCenter
            anchors.horizontalCenter: recbutton1.horizontalCenter
            text: qsTr("get image")
            color: "white"
        }

        // MouseArea to set event Onclick for FileDialog
        MouseArea{
        anchors.fill: parent
        onClicked: file.visible = true
        }
    } 

标签: qtqmlqtquickcontrols2

解决方案


您只需将处理程序添加到您的FileDialog

FileDialog {
        id: file
        title: "Choose an image"
        onAccepted: txtedit.text = fileUrl.toString().replace('file:///','')
}

推荐阅读