我基本上想從 c 端發送進度來更新 QML 大小上 ProgressBar 的值。
我正在嘗試將 QML 集成到小部件應用程式中。問題是我的 mainwindwo.cpp 檔案是這樣的:
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
QQmlContext *context = ui->quickWidget->rootContext();
QString title = "Progress Bar App";
int progress = 0;
context->setContextProperty("_myString",title); //Set Text in QML that says Hello World
timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(myFunction()));
timer->start(1000);
progress = myFunction();
context->setContextProperty("_myProgress", progress);
if(progress == 100.0){
timer->stop();
}
ui->quickWidget->setSource(QUrl("qrc:/main.qml"));
ui->quickWidget->show();
}
MainWindow::~MainWindow()
{
delete ui;
}
int MainWindow::myFunction(){
//Calculate progress
static uint16_t total_time = 50000;
static uint16_t progress = 0;
static uint16_t i = 0;
// for(double i=0; i<=total_time; i=i 1000){
// progress = ((i)*100)/total_time;
// qDebug()<<"Progress: "<<progress<<endl;
// }
if(i < total_time){
i = i 1000;
progress = ((i)*100)/total_time;
qDebug()<<"Progress: "<<progress<<endl;
}else{
qDebug()<<"Finished: "<<progress<<endl;
}
return progress;
}
我想將此處計算的進度發送到 QML 端的 ProgressBar,但我似乎無法讓它作業。
我的問題是,如果你通常創建一個帶有頭檔案和 cpp 檔案的 C 類,你如何做同樣的事情,而是使用 QTWidget 或 Mainwindow.cpp 檔案中的東西并將資料從它連續發送到 QML 檔案以更新 ProgressBar ?
uj5u.com熱心網友回復:
您必須創建一個繼承自 QObject 并且是 C 和 QML 之間的橋梁的類:
#ifndef PROGRESSBRIDGE_H
#define PROGRESSBRIDGE_H
#include <QObject>
class ProgressBridge : public QObject
{
Q_OBJECT
Q_PROPERTY(int progress READ progress WRITE setProgress NOTIFY progressChanged)
public:
explicit ProgressBridge(QObject *parent = nullptr)
: QObject{parent}, m_progress{0}
{}
int progress() const{
return m_progress;
}
void setProgress(int newProgress){
if (m_progress == newProgress)
return;
m_progress = newProgress;
emit progressChanged();
}
signals:
void progressChanged();
private:
int m_progress;
};
#endif // PROGRESSBRIDGE_H
主視窗.h
ProgressBridge progress_bridge;
主視窗.cpp
context->setContextProperty("progressBridge", &progress_bridge);
ui->quickWidget->setSource(QUrl("qrc:/main.qml"));
int MainWindow::myFunction(){
// TODO
progress_bridge.setProgress(progress);
}
在 QML 中,您確實使用 Connections
ProgressBar{
id: progressbar
from: 0.0
to: 100.0
}
Connections{
target: progressBridge
function onProgressChanged(){
progressbar.value = progressBridge.progress
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/449624.html
上一篇:QMLFileDialog可以用來從Web瀏覽器中選擇上傳檔案嗎?
下一篇:Qt中的可訪問性通知
