2017-07-06 174 views
0

好吧,我正在嘗試使用qml製作一種信使。我有一個textarea和一個發送按鈕。當單擊發送按鈕時,textarea內的文本將顯示在屏幕上的某處。但文本區域中的任何其他更改都會更改標籤的上下文。我嘗試使用createObject(...),但它沒有幫助。是否有任何其他方式動態創建標籤(或任何其他組件)?QML動態添加標籤

import QtQuick 2.7 
import QtQuick.Controls 2.0 
import QtQuick.Layouts 1.3 
import QtQuick.Controls.Material 2.1 
ApplicationWindow { 

    visible: true 
    width: 640 
    height: 480 
    property var xPosition : 500 
    property var yPosition: 200 
    title: qsTr("server") 
    Rectangle{ 
     width: parent.width 
     height: parent.height 

     Button{ 
      id: sentButton 
      width: parent.width/14 
      x: parent.height + 112 
      y: parent.width - 200 
      Material.accent: Material.Blue 
      Material.background: Material.DeepOrange 
      Text { 
       id: name 
       text: qsTr("Send") 
       color: "white" 
       x:parent.width/4 
       y:parent.height/4 
      } 
      onClicked: { 
       //add label with the context of textarea 


      } 
     } 

     Rectangle{ 
      id:back 
      height: sentButton.height 
      width: parent.width - sentButton.width 
      x:0 
      y: 435 
      color: "white" 
      border.width: 0.5 

      TextArea{ 
       id:search 
       placeholderText: qsTr("Search") 
       x:7 
       width: parent.width - 25 
       background: null 
      } 

     } 
    } 

} 
+0

['TextArea :: append'](http://doc.qt.io/qt-5/qml-qtquick-controls-textarea.html#append-method)將問題添加到您的文本中'TextArea'?你可以顯示'onClicked'裏面應該是什麼,參見[mcve] – m7913d

+0

它想要像信使一樣。所以每次點擊發送textarea的上下文都應該添加到labal(在我看來)。 – Someone

+1

使用添加內容的模型(例如'ListModel'),然後我們將標籤實例化爲代表例如。一個'ListView' – derM

回答

2

而是手動創建Label的,我想補充一個行的模型(如ListModel),並用ListView顯示。

ListView將爲模型的每一行實例化一個委託,它比手動更清潔。另外你可以免費獲得滾動行爲。

這裏舉例:

import QtQuick 2.7 
import QtQuick.Controls 2.0 
import QtQuick.Layouts 1.3 
import QtQuick.Controls.Material 2.1 

ApplicationWindow { 

    visible: true 
    width: 640 
    height: 480 
    Material.accent: Material.DeepOrange 

    ListModel { 
     id: messageModel 
    } 

    ColumnLayout { 
     anchors { fill: parent; margins: 8 } 
     spacing: 16 
     ListView { 
      Layout.fillWidth: true; Layout.fillHeight: true 
      model: messageModel 
      delegate: ItemDelegate { text: model.message } 
     } 
     RowLayout { 
      spacing: 16 
      Layout.fillWidth: true; Layout.fillHeight: false 
      TextField { 
       id: textField 
       Layout.fillWidth: true; Layout.fillHeight: true 
      } 
      Button { 
       Material.foreground: "white"; Material.background: Material.DeepOrange 
       Layout.fillHeight: true 
       text: "Send" 
       onClicked: { 
        messageModel.append({message: textField.text}); 
        textField.text = ""; 
       } 
      } 
     } 
    } 
} 

這裏,Button將追加一個新行ListModelTextFieldtext爲消息作用。 然後ListView爲模型的每一行實例化一個顯示消息角色的ItemDelegate

+0

工作 - 非常感謝 – Someone