qt與js互相調用

來源:互聯網
上載者:User

標籤:

二、QT支援Js流程

QT與JavaScript互調是通過QWebFrame的兩個函數來實現的:addToJavaScriptWindowObject()將QObject對象傳給JS,這樣JS就能調用QObject的public slots函數。QT通過evaluateJavaScript()直接調用JS中的函數。流程如下(《QT進階編程》中插圖):

 

 

 

三、樣本

使用QWebKit建立一個包含瀏覽器和工具按鈕視窗,在該瀏覽器中載入包括Js的html,工具按鈕調用html中的js

1、工程中引入 webkit

   工程檔案中增加加:QT += webkit network

2、載入html網頁

m_pWebView = new QWebView;

    m_pWebView->load(QUrl(tr("G:\\html特效樣本\\jsTest.html")));

3、開戶js支援

    QWebSettings *pWebSettings = m_pWebView->page()->settings();       

    pWebSettings->setAttribute(QWebSettings::JavascriptEnabled,true);

4、表單布局

//添加按鈕    

    QPushButton *pEventBtn = new QPushButton(tr("QT Invok Js"));   

    QPushButton *pcloseBtn = new QPushButton(tr("close"));

//布局:網頁與按鈕為上下布局,兩按鈕為水平置中布局  

 

    QHBoxLayout *pBtnLayout = new QHBoxLayout; 

    pBtnLayout->addWidget(pEventBtn);  

    pBtnLayout->addWidget(pcloseBtn);  

    pBtnLayout->setAlignment(Qt::AlignCenter);   

 

    QVBoxLayout *pMainLayout = new QVBoxLayout; 

   pMainLayout->addWidget(m_pWebView);  

    pMainLayout->addLayout(pBtnLayout);  

 

    QWidget *widget = new QWidget;  

    widget->setLayout(pMainLayout);  

    setCentralWidget(widget);

 

5、建立訊號與槽

//每次載入html時發送段訊號    

    connect(m_pWebView->page()->mainFrame(),SIGNAL(javaScriptWindowObjectCleared()),  this,SLOT(addObjectToJs()));    

//按鈕訊號    

    connect(pEventBtn,SIGNAL(clicked()),this,SLOT(testJs()));    

    connect(pcloseBtn,SIGNAL(clicked()),this,SLOT(close()));

 

6、JS調用QT中的public slots

6.1、標頭檔中申明public slots:

public slots:   

    void jsInvokQt();   

 

 

6.2、將QObject與js綁定

void MainWindow::addObjectToJs()

{

     m_pWebView->page()->mainFrame()->addToJavaScriptWindowObject("MainWindow",this);

}

6.3、Js中調用QT的 jsInvokQt()函數

function disp_qtmessage()

{

        MainWindow.jsInvokQt();

}

7、QT調用JS函數disp_messagebox()

void MainWindow::testJs()

{    

    m_pWebView->page()->mainFrame()->evaluateJavaScript("disp_messagebox()");

}

 

四、附含JS的html源碼:

<html>

<head>

<script type="text/javascript">

function disp_messagebox()

{

alert("This is javaScript MessageBox!")

}

 

function disp_qtmessage()

{

  MainWindow.jsInvokQt();

   MainWindow.setInfor("Qt change string"); 

   alert(MainWindow.getInfor());

}

 

</script>

</head>

<body>

 

<input type="button" onclick="disp_qtmessage()" value="InvokQt" />

 

</body>

</html>

qt與js互相調用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.