qt的qreal和double什么区别,没有区别,只是增加阅读性

typedef double qreal;在这里插入图片描述
ai是这么回答的
在这里插入图片描述

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
#include <QAction> #include <QApplication> #include <QClipboard> #include <QColorDialog> #include <QComboBox> #include <QFontComboBox> #include <QFile> #include <QFileDialog> #include <QFileInfo> #include <QFontDatabase> #include <QMenu> #include <QMenuBar> #include <QTextCodec> #include <QTextEdit> #include <QToolBar> #include <QTextCursor> #include <QTextDocumentWriter> #include <QTextList> #include <QtDebug> #include <QCloseEvent> #include <QMessageBox> #include <QMimeData> #ifndef QT_NO_PRINTER #include <QPrintDialog> #include <QPrinter> #include <QPrintPreviewDialog> #endif #include "textedit.h" #ifdef Q_OS_MAC const QString rsrcPath = ":/images/mac"; #else const QString rsrcPath = ":/images/win"; #endif TextEdit::TextEdit(QWidget *parent) : QMainWindow(parent) { #ifdef Q_OS_OSX setUnifiedTitleAndToolBarOnMac(true); #endif setToolButtonStyle(Qt::ToolButtonFollowStyle); setupFileActions(); setupEditActions(); setupTextActions(); { QMenu *helpMenu = new QMenu(tr("Help"), this); menuBar()->addMenu(helpMenu); helpMenu->addAction(tr("About"), this, SLOT(about())); helpMenu->addAction(tr("About &Qt"), qApp, SLOT(aboutQt())); } textEdit = new QTextEdit(this); connect(textEdit, SIGNAL(currentCharFormatChanged(QTextCharFormat)), this, SLOT(currentCharFormatChanged(QTextCharFormat))); connect(textEdit, SIGNAL(cursorPositionChanged()), this, SLOT(cursorPositionChanged())); setCentralWidget(textEdit); textEdit->setFocus(); setCurrentFileName(QString()); QFont textFont("Helvetica"); textFont.setStyleHint(QFont::SansSerif); textEdit->setFont(textFont); fontChanged(textEdit->font()); colorChanged(textEdit->textColor()); alignmentChanged(textEdit->alignment()); connect(textEdit->document(), SIGNAL(modificationChanged(bool)), actionSave, SLOT(setEnabled(bool))); connect(textEdit->document(), SIGNAL(modificationChanged(bool)), this, SLOT(setWindowModified(bool))); connect(textEdit->document(), SIGNAL(undoAvailable(bool)), actionUndo, SLOT(setEnabled(bool))); connect(textEdit->document(), SIGNAL(redoAvailable(bool)), actionRedo, SLOT(setEnabled(bool))); setWindowModified(textEdit->document()->isModified()); actionSave->setEnabled(textEdit->document()->isModified()); actionUndo->setEnabled(textEdit->document()->isUndoAvailable()); actionRedo->setEnabled(textEdit->document()->isRedoAvailable()); connect(actionUndo, SIGNAL(triggered()), textEdit, SLOT(undo())); connect(actionRedo, SIGNAL(triggered()), textEdit, SLOT(redo())); actionCut->setEnabled(false); actionCopy->setEnabled(false); connect(actionCut, SIGNAL(triggered()), textEdit, SLOT(cut())); connect(actionCopy, SIGNAL(triggered()), textEdit, SLOT(copy())); connect(actionPaste, SIGNAL(triggered()), textEdit, SLOT(paste())); connect(textEdit, SIGNAL(copyAvailable(bool)), actionCut, SLOT(setEnabled(bool))); connect(textEdit, SIGNAL(copyAvailable(bool)), actionCopy, SLOT(setEnabled(bool))); #ifndef QT_NO_CLIPBOARD connect(QApplication::clipboard(), SIGNAL(dataChanged()), this, SLOT(clipboardDataChanged())); #endif QString initialFile = ":/example.html"; const QStringList args = QCoreApplication::arguments(); if (args.count() == 2) initialFile = args.at(1); if (!load(initialFile)) fileNew(); } void TextEdit::closeEvent(QCloseEvent *e) { if (maybeSave()) e->accept(); else e->ignore(); } void TextEdit::setupFileActions() { QToolBar *tb = new QToolBar(this); tb->setWindowTitle(tr("File Actions")); addToolBar(tb); QMenu *menu = new QMenu(tr("&File"), this); menuBar()->addMenu(menu); QAction *a; QIcon newIcon = QIcon::fromTheme("document-new", QIcon(rsrcPath + "/filenew.png")); a = new QAction( newIcon, tr("&New"), this); a->setPriority(QAction::LowPriority); a->setShortcut(QKeySequence::New); connect(a, SIGNAL(triggered()), this, SLOT(fileNew())); tb->addAction(a); menu->addAction(a); a = new QAction(QIcon::fromTheme("document-open", QIcon(rsrcPath + "/fileopen.png")), tr("&Open..."), this); a->setShortcut(QKeySequence::Open); connect(a, SIGNAL(triggered()), this, SLOT(fileOpen())); tb->addAction(a); menu->addAction(a); menu->addSeparator(); actionSave = a = new QAction(QIcon::fromTheme("document-save", QIcon(rsrcPath + "/filesave.png")), tr("&Save"), this); a->setShortcut(QKeySequence::Save); connect(a, SIGNAL(triggered()), this, SLOT(fileSave())); a->setEnabled(false); tb->addAction(a); menu->addAction(a); a = new QAction(tr("Save &As..."), this); a->setPriority(QAction::LowPriority); connect(a, SIGNAL(triggered()), this, SLOT(fileSaveAs())); menu->addAction(a); menu->addSeparator(); #ifndef QT_NO_PRINTER a = new QAction(QIcon::fromTheme("document-print", QIcon(rsrcPath + "/fileprint.png")), tr("&Print..."), this); a->setPriority(QAction::LowPriority); a->setShortcut(QKeySequence::Print); connect(a, SIGNAL(triggered()), this, SLOT(filePrint())); tb->addAction(a); menu->addAction(a); a = new QAction(QIcon::fromTheme("fileprint", QIcon(rsrcPath + "/fileprint.png")), tr("Print Preview..."), this); connect(a, SIGNAL(triggered()), this, SLOT(filePrintPreview())); menu->addAction(a); a = new QAction(QIcon::fromTheme("exportpdf", QIcon(rsrcPath + "/exportpdf.png")), tr("&Export PDF..."), this); a->setPriority(QAction::LowPriority); a->setShortcut(Qt::CTRL + Qt::Key_D); connect(a, SIGNAL(triggered()), this, SLOT(filePrintPdf())); tb->addAction(a); menu->addAction(a); menu->addSeparator(); #endif a = new QAction(tr("&Quit"), this); a->setShortcut(Qt::CTRL + Qt::Key_Q); connect(a, SIGNAL(triggered()), this, SLOT(close())); menu->addAction(a); } void TextEdit::setupEditActions() { QToolBar *tb = new QToolBar(this); tb->setWindowTitle(tr("Edit Actions")); addToolBar(tb); QMenu *menu = new QMenu(tr("&Edit"), this); menuBar()->addMenu(menu); QAction *a; a = actionUndo = new QAction(QIcon::fromTheme("edit-undo", QIcon(rsrcPath + "/editundo.png")), tr("&Undo"), this); a->setShortcut(QKeySequence::Undo); tb->addAction(a); menu->addAction(a); a = actionRedo = new QAction(QIcon::fromTheme("edit-redo", QIcon(rsrcPath + "/editredo.png")), tr("&Redo"), this); a->setPriority(QAction::LowPriority); a->setShortcut(QKeySequence::Redo); tb->addAction(a); menu->addAction(a); menu->addSeparator(); a = actionCut = new QAction(QIcon::fromTheme("edit-cut", QIcon(rsrcPath + "/editcut.png")), tr("Cu&t"), this); a->setPriority(QAction::LowPriority); a->setShortcut(QKeySequence::Cut); tb->addAction(a); menu->addAction(a); a = actionCopy = new QAction(QIcon::fromTheme("edit-copy", QIcon(rsrcPath + "/editcopy.png")), tr("&Copy"), this); a->setPriority(QAction::LowPriority); a->setShortcut(QKeySequence::Copy); tb->addAction(a); menu->addAction(a); a = actionPaste = new QAction(QIcon::fromTheme("edit-paste", QIcon(rsrcPath + "/editpaste.png")), tr("&Paste"), this); a->setPriority(QAction::LowPriority); a->setShortcut(QKeySequence::Paste); tb->addAction(a); menu->addAction(a); #ifndef QT_NO_CLIPBOARD if (const QMimeData *md = QApplication::clipboard()->mimeData()) actionPaste->setEnabled(md->hasText()); #endif } void TextEdit::setupTextActions() { QToolBar *tb = new QToolBar(this); tb->setWindowTitle(tr("Format Actions")); addToolBar(tb); QMenu *menu = new QMenu(tr("F&ormat"), this); menuBar()->addMenu(menu); actionTextBold = new QAction(QIcon::fromTheme("format-text-bold", QIcon(rsrcPath + "/textbold.png")), tr("&Bold"), this); actionTextBold->setShortcut(Qt::CTRL + Qt::Key_B); actionTextBold->setPriority(QAction::LowPriority); QFont bold; bold.setBold(true); actionTextBold->setFont(bold); connect(actionTextBold, SIGNAL(triggered()), this, SLOT(textBold())); tb->addAction(actionTextBold); menu->addAction(actionTextBold); actionTextBold->setCheckable(true); actionTextItalic = new QAction(QIcon::fromTheme("format-text-italic", QIcon(rsrcPath + "/textitalic.png")), tr("&Italic"), this); actionTextItalic->setPriority(QAction::LowPriority); actionTextItalic->setShortcut(Qt::CTRL + Qt::Key_I); QFont italic; italic.setItalic(true); actionTextItalic->setFont(italic); connect(actionTextItalic, SIGNAL(triggered()), this, SLOT(textItalic())); tb->addAction(actionTextItalic); menu->addAction(actionTextItalic); actionTextItalic->setCheckable(true); actionTextUnderline = new QAction(QIcon::fromTheme("format-text-underline", QIcon(rsrcPath + "/textunder.png")), tr("&Underline"), this); actionTextUnderline->setShortcut(Qt::CTRL + Qt::Key_U); actionTextUnderline->setPriority(QAction::LowPriority); QFont underline; underline.setUnderline(true); actionTextUnderline->setFont(underline); connect(actionTextUnderline, SIGNAL(triggered()), this, SLOT(textUnderline())); tb->addAction(actionTextUnderline); menu->addAction(actionTextUnderline); actionTextUnderline->setCheckable(true); menu->addSeparator(); QActionGroup *grp = new QActionGroup(this); connect(grp, SIGNAL(triggered(QAction*)), this, SLOT(textAlign(QAction*))); // Make sure the alignLeft is always left of the alignRight if (QApplication::isLeftToRight()) { actionAlignLeft = new QAction(QIcon::fromTheme("format-justify-left", QIcon(rsrcPath + "/textleft.png")), tr("&Left"), grp); actionAlignCenter = new QAction(QIcon::fromTheme("format-justify-center", QIcon(rsrcPath + "/textcenter.png")), tr("C&enter"), grp); actionAlignRight = new QAction(QIcon::fromTheme("format-justify-right", QIcon(rsrcPath + "/textright.png")), tr("&Right"), grp); } else { actionAlignRight = new QAction(QIcon::fromTheme("format-justify-right", QIcon(rsrcPath + "/textright.png")), tr("&Right"), grp); actionAlignCenter = new QAction(QIcon::fromTheme("format-justify-center", QIcon(rsrcPath + "/textcenter.png")), tr("C&enter"), grp); actionAlignLeft = new QAction(QIcon::fromTheme("format-justify-left", QIcon(rsrcPath + "/textleft.png")), tr("&Left"), grp); } actionAlignJustify = new QAction(QIcon::fromTheme("format-justify-fill", QIcon(rsrcPath + "/textjustify.png")), tr("&Justify"), grp); actionAlignLeft->setShortcut(Qt::CTRL + Qt::Key_L); actionAlignLeft->setCheckable(true); actionAlignLeft->setPriority(QAction::LowPriority); actionAlignCenter->setShortcut(Qt::CTRL + Qt::Key_E); actionAlignCenter->setCheckable(true); actionAlignCenter->setPriority(QAction::LowPriority); actionAlignRight->setShortcut(Qt::CTRL + Qt::Key_R); actionAlignRight->setCheckable(true); actionAlignRight->setPriority(QAction::LowPriority); actionAlignJustify->setShortcut(Qt::CTRL + Qt::Key_J); actionAlignJustify->setCheckable(true); actionAlignJustify->setPriority(QAction::LowPriority); tb->addActions(grp->actions()); menu->addActions(grp->actions()); menu->addSeparator(); QPixmap pix(16, 16); pix.fill(Qt::black); actionTextColor = new QAction(pix, tr("&Color..."), this); connect(actionTextColor, SIGNAL(triggered()), this, SLOT(textColor())); tb->addAction(actionTextColor); menu->addAction(actionTextColor); tb = new QToolBar(this); tb->setAllowedAreas(Qt::TopToolBarArea | Qt::BottomToolBarArea); tb->setWindowTitle(tr("Format Actions")); addToolBarBreak(Qt::TopToolBarArea); addToolBar(tb); comboStyle = new QComboBox(tb); tb->addWidget(comboStyle); comboStyle->addItem("Standard"); comboStyle->addItem("Bullet List (Disc)"); comboStyle->addItem("Bullet List (Circle)"); comboStyle->addItem("Bullet List (Square)"); comboStyle->addItem("Ordered List (Decimal)"); comboStyle->addItem("Ordered List (Alpha lower)"); comboStyle->addItem("Ordered List (Alpha upper)"); comboStyle->addItem("Ordered List (Roman lower)"); comboStyle->addItem("Ordered List (Roman upper)"); connect(comboStyle, SIGNAL(activated(int)), this, SLOT(textStyle(int))); comboFont = new QFontComboBox(tb); tb->addWidget(comboFont); connect(comboFont, SIGNAL(activated(QString)), this, SLOT(textFamily(QString))); comboSize = new QComboBox(tb); comboSize->setObjectName("comboSize"); tb->addWidget(comboSize); comboSize->setEditable(true); QFontDatabase db; foreach(int size, db.standardSizes()) comboSize->addItem(QString::number(size)); connect(comboSize, SIGNAL(activated(QString)), this, SLOT(textSize(QString))); comboSize->setCurrentIndex(comboSize->findText(QString::number(QApplication::font() .pointSize()))); } bool TextEdit::load(const QString &f) { if (!QFile::exists(f)) return false; QFile file(f); if (!file.open(QFile::ReadOnly)) return false; QByteArray data = file.readAll(); QTextCodec *codec = Qt::codecForHtml(data); QString str = codec->toUnicode(data); if (Qt::mightBeRichText(str)) { textEdit->setHtml(str); } else { str = QString::fromLocal8Bit(data); textEdit->setPlainText(str); } setCurrentFileName(f); return true; } bool TextEdit::maybeSave() { if (!textEdit->document()->isModified()) return true; QMessageBox::StandardButton ret; ret = QMessageBox::warning(this, tr("Application"), tr("The document has been modified.\n" "Do you want to save your changes?"), QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel); if (ret == QMessageBox::Save) return fileSave(); else if (ret == QMessageBox::Cancel) return false; return true; } void TextEdit::setCurrentFileName(const QString &fileName) { this->fileName = fileName; textEdit->document()->setModified(false); QString shownName; if (fileName.isEmpty()) shownName = "untitled.txt"; else shownName = QFileInfo(fileName).fileName(); setWindowTitle(tr("%1[*] - %2").arg(shownName).arg(tr("Rich Text"))); setWindowModified(false); } void TextEdit::fileNew() { if (maybeSave()) { textEdit->clear(); setCurrentFileName(QString()); } } void TextEdit::fileOpen() { QString fn = QFileDialog::getOpenFileName(this, tr("Open File..."), QString(), tr("HTML-Files (*.htm *.html);;All Files (*)")); if (!fn.isEmpty()) load(fn); } bool TextEdit::fileSave() { if (fileName.isEmpty()) return fileSaveAs(); if (fileName.startsWith(QStringLiteral(":/"))) return fileSaveAs(); QTextDocumentWriter writer(fileName); bool success = writer.write(textEdit->document()); if (success) textEdit->document()->setModified(false); return success; } bool TextEdit::fileSaveAs() { QString fn = QFileDialog::getSaveFileName(this, tr("Save as..."), QString(), tr("ODF files (*.odt);;HTML-Files " "(*.htm *.html);;All Files (*)")); if (fn.isEmpty()) return false; if (!(fn.endsWith(".odt", Qt::CaseInsensitive) || fn.endsWith(".htm", Qt::CaseInsensitive) || fn.endsWith(".html", Qt::CaseInsensitive))) { fn += ".odt"; // default } setCurrentFileName(fn); return fileSave(); } void TextEdit::filePrint() { #if !defined(QT_NO_PRINTER) && !defined(QT_NO_PRINTDIALOG) QPrinter printer(QPrinter::HighResolution); QPrintDialog *dlg = new QPrintDialog(&printer, this); if (textEdit->textCursor().hasSelection()) dlg->addEnabledOption(QAbstractPrintDialog::PrintSelection); dlg->setWindowTitle(tr("Print Document")); if (dlg->exec() == QDialog::Accepted) textEdit->print(&printer); delete dlg; #endif } void TextEdit::filePrintPreview() { #if !defined(QT_NO_PRINTER) && !defined(QT_NO_PRINTDIALOG) QPrinter printer(QPrinter::HighResolution); QPrintPreviewDialog preview(&printer, this); connect(&preview, SIGNAL(paintRequested(QPrinter*)), SLOT(printPreview(QPrinter*))); preview.exec(); #endif } void TextEdit::printPreview(QPrinter *printer) { #ifdef QT_NO_PRINTER Q_UNUSED(printer); #else textEdit->print(printer); #endif } void TextEdit::filePrintPdf() { #ifndef QT_NO_PRINTER QString fileName = QFileDialog::getSaveFileName(this, "Export PDF", QString(), "*.pdf"); if (!fileName.isEmpty()) { if (QFileInfo(fileName).suffix().isEmpty()) fileName.append(".pdf"); QPrinter printer(QPrinter::HighResolution); printer.setOutputFormat(QPrinter::PdfFormat); printer.setOutputFileName(fileName); textEdit->document()->print(&printer); } #endif } void TextEdit::textBold() { QTextCharFormat fmt; fmt.setFontWeight(actionTextBold->isChecked() ? QFont::Bold : QFont::Normal); mergeFormatOnWordOrSelection(fmt); } void TextEdit::textUnderline() { QTextCharFormat fmt; fmt.setFontUnderline(actionTextUnderline->isChecked()); mergeFormatOnWordOrSelection(fmt); } void TextEdit::textItalic() { QTextCharFormat fmt; fmt.setFontItalic(actionTextItalic->isChecked()); mergeFormatOnWordOrSelection(fmt); } void TextEdit::textFamily(const QString &f) { QTextCharFormat fmt; fmt.setFontFamily(f); mergeFormatOnWordOrSelection(fmt); } void TextEdit::textSize(const QString &p) { qreal pointSize = p.toFloat(); if (p.toFloat() > 0) { QTextCharFormat fmt; fmt.setFontPointSize(pointSize); mergeFormatOnWordOrSelection(fmt); } } void TextEdit::textStyle(int styleIndex) { QTextCursor cursor = textEdit->textCursor(); if (styleIndex != 0) { QTextListFormat::Style style = QTextListFormat::ListDisc; switch (styleIndex) { default: case 1: style = QTextListFormat::ListDisc; break; case 2: style = QTextListFormat::ListCircle; break; case 3: style = QTextListFormat::ListSquare; break; case 4: style = QTextListFormat::ListDecimal; break; case 5: style = QTextListFormat::ListLowerAlpha; break; case 6: style = QTextListFormat::ListUpperAlpha; break; case 7: style = QTextListFormat::ListLowerRoman; break; case 8: style = QTextListFormat::ListUpperRoman; break; } cursor.beginEditBlock(); QTextBlockFormat blockFmt = cursor.blockFormat(); QTextListFormat listFmt; if (cursor.currentList()) { listFmt = cursor.currentList()->format(); } else { listFmt.setIndent(blockFmt.indent() + 1); blockFmt.setIndent(0); cursor.setBlockFormat(blockFmt); } listFmt.setStyle(style); cursor.createList(listFmt); cursor.endEditBlock(); } else { // #### QTextBlockFormat bfmt; bfmt.setObjectIndex(-1); cursor.mergeBlockFormat(bfmt); } } void TextEdit::textColor() { QColor col = QColorDialog::getColor(textEdit->textColor(), this); if (!col.isValid()) return; QTextCharFormat fmt; fmt.setForeground(col); mergeFormatOnWordOrSelection(fmt); colorChanged(col); } void TextEdit::textAlign(QAction *a) { if (a == actionAlignLeft) textEdit->setAlignment(Qt::AlignLeft | Qt::AlignAbsolute); else if (a == actionAlignCenter) textEdit->setAlignment(Qt::AlignHCenter); else if (a == actionAlignRight) textEdit->setAlignment(Qt::AlignRight | Qt::AlignAbsolute); else if (a == actionAlignJustify) textEdit->setAlignment(Qt::AlignJustify); } void TextEdit::currentCharFormatChanged(const QTextCharFormat &format) { fontChanged(format.font()); colorChanged(format.foreground().color()); } void TextEdit::cursorPositionChanged() { alignmentChanged(textEdit->alignment()); } void TextEdit::clipboardDataChanged() { #ifndef QT_NO_CLIPBOARD if (const QMimeData *md = QApplication::clipboard()->mimeData()) actionPaste->setEnabled(md->hasText()); #endif } void TextEdit::about() { QMessageBox::about(this, tr("About"), tr("This example demonstrates Qt's " "rich text editing facilities in action, providing an example " "document for you to experiment with.")); } void TextEdit::mergeFormatOnWordOrSelection(const QTextCharFormat &format) { QTextCursor cursor = textEdit->textCursor(); if (!cursor.hasSelection()) cursor.select(QTextCursor::WordUnderCursor); cursor.mergeCharFormat(format); textEdit->mergeCurrentCharFormat(format); } void TextEdit::fontChanged(const QFont &f) { comboFont->setCurrentIndex(comboFont->findText(QFontInfo(f).family())); comboSize->setCurrentIndex(comboSize->findText(QString::number(f.pointSize()))); actionTextBold->setChecked(f.bold()); actionTextItalic->setChecked(f.italic()); actionTextUnderline->setChecked(f.underline()); } void TextEdit::colorChanged(const QColor &c) { QPixmap pix(16, 16); pix.fill(c); actionTextColor->setIcon(pix); } void TextEdit::alignmentChanged(Qt::Alignment a) { if (a & Qt::AlignLeft) actionAlignLeft->setChecked(true); else if (a & Qt::AlignHCenter) actionAlignCenter->setChecked(true); else if (a & Qt::AlignRight) actionAlignRight->setChecked(true); else if (a & Qt::AlignJustify) actionAlignJustify->setChecked(true); }
在C++程序中使用QML QML API是分为三个主类——QDeclarativeEngine, QdeclarativeComponent 与 QDeclarativeContext。QDeclarativeEngine 提供QML运行的环境,QdeclarativeComponent 封装了QML Documents 与QDeclarativeContext允许程序导出数据到QML组件实例。 QML还包含了API的一个方便,通过QDeclarativeView 应用程序只需要简单嵌入QML组件到一个新的QGraphicsView就可以了。这有许多细节将在下面讨论。QDeclarativeView 主要是用于快速成型的应用程序里。 如果你是重新改进使用QML的Qt应用程序,请参阅 整合QML到现有的Qt UI代码。 基本用法 每个应用程序至少需求一个QDeclarativeEngine。QDeclarativeEngine允许配置全局设置应用到所有的QML组件实例中,例如QNetworkAccessManager是用于网络通信以及永久储存的路径。如果应用程序需求在QML组件实例间需求不同的设置只需要多个QDeclarativeEngine。 使用QDeclarativeComponent类载入QML Documents。每个QDeclarativeComponent实例呈现单一QML文档。QDeclarativeComponent可以传递一个文档的地址或文档的原始文本内容。该文档的URL可以是本地文件系统的地址或通过QNetworkAccessManager支持的网络地址。 QML组件实例通过调用QDeclarativeComponent::create()模式来创建。在这里载入一个QML文档的示例并且从它这里创建一个对象。 QDeclarativeEngine *engine = new QDeclarativeEngine(parent); QDeclarativeComponent component(engine, QUrl::fromLocalFile(“main.qml”)); QObject *myObject = component.create(); 导出数据 QML组件是以QDeclarativeContext实例化的。context允许应用程序导出数据到该QML组件实例中。单个QDeclarativeContext 可用于一应用程序的所有实例对象或针对每个实例使用QDeclarativeContext 可以创建更为精确的控制导出数据。如果不传递一个context给QDeclarativeComponent::create()模式;那么将使用QDeclarativeEngine的root context。数据导出通过该root context对所有对象实例是有效的。 简单数据 为了导出数据到一个QML组件实例,应用程序设置Context属;然后由QML属绑定的名称与JavaScrip访问。下面的例子显示通过QGraphicsView如何导出一个背景颜色到QML文件中: //main.cpp #include <QApplication> #include <QDeclarativeView> #include <QDeclarativeContext> int main(int argc, char *argv[]) { QApplication app(argc, argv); QDeclarativeView view; QDeclarativeContext *context = view.rootContext(); context->setContextProperty(“backgroundColor”, QColor(Qt::yellow)); view.setSource(QUrl::fromLocalFile(“main.qml”)); view.show(); return app.exec(); } //main.qml import Qt 4.7 Rectangle { width: 300 height: 300 color: backgroundColor Text { anchors.centerIn: parent text: “Hello Yellow World!” } } 或者,如果你需要main.cpp不需要在QDeclarativeView显示创建的组件,你就需要使用QDeclarativeEngine::rootContext()替代创建QDeclarativeContext实例。 QDeclarativeEngine engine; QDeclarativeContext *windowContext = new QDeclarativeContext(engine.rootContext()); windowContext->setContextProperty(“backgroundColor”, QColor(Qt::yellow)); QDeclarativeComponent component(&engine, “main.qml”); QObject *window = component.create(windowContext); Context属的操作像QML绑定的标准属那样——在这个例子中的backgroundColor Context属改变为红色;那么该组件对象实例将自动更新。注意:删除任意QDeclarativeContext的构造是创建者的事情。当window组件实例撤消时不再需要windowContext时,windowContext必须被消毁。最简单的方法是确保它设置window作为windowContext的父级。 QDeclarativeContexts 是树形结构——除了root context每个QDeclarativeContexts都有一个父级。子级QDeclarativeContexts有效的继承它们父级的context属。这使应用程序分隔不同数据导出到不同的QML对象实例有更多自由。如果QDeclarativeContext设置一context属,同样它父级也被影响,新的context属是父级的影子。如下例子中,background context属是Context 1,也是root context里background context属的影子。 结构化数据 context属同样可用于输出结构化与写数据到QML对象。除了QVariant支持所有已经存在的类型外,QObject 派生类型可以分配给context属。 QObject context属允许数据结构化输出并允许QML来设置值。 下例创建CustomPalette对象并设置它作为palette context属。 class CustomPalette : public QObject { Q_OBJECT Q_PROPERTY(QColor background READ background WRITE setBackground NOTIFY backgroundChanged) Q_PROPERTY(QColor text READ text WRITE setText NOTIFY textChanged) public: CustomPalette() : m_background(Qt::white), m_text(Qt::black) {} QColor background() const { return m_background; } void setBackground(const QColor &c) { if (c != m_background) { m_background = c; emit backgroundChanged(); } } QColor text() const { return m_text; } void setText(const QColor &c) { if (c != m_text) { m_text = c; emit textChanged(); } } signals: void textChanged(); void backgroundChanged(); private: QColor m_background; QColor m_text; }; int main(int argc, char *argv[]) { QApplication app(argc, argv); QDeclarativeView view; view.rootContext()->setContextProperty(“palette”, new CustomPalette); view.setSource(QUrl::fromLocalFile(“main.qml”)); view.show(); return app.exec(); } QML引用palette对象以及它的属,为了设置背景与文本的颜色,这里是当单击窗口时,面板的文本颜色将改变成蓝色。 import Qt 4.7 Rectangle { width: 240 height: 320 color: palette.background Text { anchors.centerIn: parent color: palette.text text: “Click me to change color!” } MouseArea { anchors.fill: parent onClicked: { palette.text = “blue”; } } } 可以检测一个C++属值——这种情况下的CustomPalette的文本属改变,该属必须有相应的NOTIFY信息。NOTIFY信号是属值改变时将指定一个信号发射。 实现者应该注意的是,只有值改变时才发射信号,以防止发生死循环。访问一个绑定的属,没有NOTIFY信号的话,将导致QML在运行时发出警告信息。 动态结构化数据 如果应用程序对结构化过于动态编译QObject类型;那么对动态结构化数据可在运行时使用QDeclarativePropertyMap 类构造。 从QML调用 C++ 通过public slots输出模式或Q_INVOKABLE标记模式使它可以调用QObject派生出的类型。 C++模式同样可以有参数并且可以返回值。QML支持如下类型: •bool •unsigned int, int •float, double, qreal •QString •QUrl •QColor •QDate,QTime,QDateTime •QPoint,QPointF •QSize,QSizeF •QRect,QRectF •QVariant 下面例子演示了,当MouseArea单击时控制“Stopwatch”对象的开关。 //main.cpp class Stopwatch : public QObject { Q_OBJECT public: Stopwatch(); Q_INVOKABLE bool isRunning() const; public slots: void start(); void stop(); private: bool m_running; }; int main(int argc, char *argv[]) { QApplication app(argc, argv); QDeclarativeView view; view.rootContext()->setContextProperty(“stopwatch”, new Stopwatch); view.setSource(QUrl::fromLocalFile(“main.qml”)); view.show(); return app.exec(); } //main.qml import Qt 4.7 Rectangle { width: 300 height: 300 MouseArea { anchors.fill: parent onClicked: { if (stopwatch.isRunning()) stopwatch.stop() else stopwatch.start(); } } } 值得注意的是,在这个特殊的例子里有更好的方法来达到同样的效果,在main.qml有”running”属,这将会是一个非常优秀的QML代码: // main.qml import Qt 4.7 Rectangle { MouseArea { anchors.fill: parent onClicked: stopwatch.running = !stopwatch.running } } 当然,它同样可以调用 functions declared in QML from C++。 网络组件 如果URL传递给QDeclarativeComponent是一网络资源或者QML文档引用一网络资源,QDeclarativeComponent要先获取网络数据;然后才可以创建对象。在这种情况下QDeclarativeComponent将有Loading status。直到组件调用QDeclarativeComponent::create()之前,应用程序将一直等待。 下面的例子显示如何从一个网络资源载入QML文件。在创建QDeclarativeComponent之后,它测试组件是否加载。如果是,它连接QDeclarativeComponent::statusChanged()信号,否则直接调用continueLoading()。这个测试是必要的,甚至URL都可以是远程的,只是在这种情况下要防组件是被缓存的。 MyApplication::MyApplication() { // … component = new QDeclarativeComponent(engine, QUrl(“http://www.example.com/main.qml”)); if (component->isLoading()) QObject::connect(component, SIGNAL(statusChanged(QDeclarativeComponent::Status)), this, SLOT(continueLoading())); else continueLoading(); } void MyApplication::continueLoading() { if (component->isError()) { qWarning() << component->errors(); } else { QObject *myObject = component->create(); } } Qt资源 QML的内容可以使用qrc:URL方案从Qt 资源系统载入。例如: [project/example.qrc] <!DOCTYPE RCC> <RCC version=”1.0″> <qresource prefix=”/”> <file>main.qml</file> <file>images/background.png</file> </qresource> </RCC> [project/project.pro] QT += declarative SOURCES += main.cpp RESOURCES += example.qrc [project/main.cpp] int main(int argc, char *argv[]) { QApplication app(argc, argv); QDeclarativeView view; view.setSource(QUrl(“qrc:/main.qml”)); view.show(); return app.exec(); } [project/main.qml] import Qt 4.7 Image { source: “images/background.png” } 请注意,资源系统是不能从QML直接访问的。如果主QML文件被加载作为资源,所有的文件指定在QML中做为相对路径从资源系统载入。在QML层使用资源系统是完全透明的。这也意味着,如果主QML文件没有被加载作为资源,那么从QML不能访问资源系统。 1.这里主要是介绍,如何在c++中调用QML中的函数和设置QML中的属的问题 2.具体代码 // UICtest.qml import Qt 4.7 Rectangle { id: mainWidget; width: 640 height: 480 function callbyc(v) { mainWidget.color = v; return "finish"; } Rectangle{ id: secondRect; x: 100; y: 20; width: 400; height: 300; Rectangle{ x: 10; y: 20; width: 30; height: 40; color: "#FF035721" Text { objectName: "NeedFindObj"; anchors.fill: parent; text: ""; } } } } // main.cpp #include <QtGui/QApplication> #include <QtDeclarative/QDeclarativeView> #include <QtDeclarative/QDeclarativeEngine> #include <QtDeclarative/QDeclarativeComponent> #include <QtDeclarative/QDeclarativeContext> #include <QtDeclarative/QDeclarativeItem> #include <QMetaObject> int main(int argc, char *argv[]) { QApplication a(argc, argv); QDeclarativeView qmlView; qmlView.setSource(QUrl::fromLocalFile("../UICtest/UICtest.qml")); qmlView.show(); // 获取根节点,就是 QML中 id是mainWidget的节点 QDeclarativeItem *item = qobject_cast<QDeclarativeItem*>(qmlView.rootObject()); item->setProperty("color", QVariant("blue")); // 查找到我们需要的节点根均objectname NeedFindObj 来获得,并设置他的文本属 QDeclarativeItem *item1 = item->findChild<QDeclarativeItem *>("NeedFindObj"); if (item1) { item1->setProperty("text", QVariant("OK")); } // 调用QML中的函数, 分别是 函数所在的对象, 函数名,返回值, 参数 QVariant returnVar; QVariant arg1 = "blue"; QMetaObject::invokeMethod(item, "callbyc", Q_RETURN_ARG(QVariant, returnVar),Q_ARG(QVariant, arg1)); qDebug(" %s",returnVar.toString().toLocal8Bit().data()); return a.exec(); } 说明: 这里的根节点是id为mainWidget的矩形元素,那么在C++中获取根节点后就可以,直接的设置他的属了。其他属也可以同样,调用指定节点内的函数是通过QMetaObject中的invokeMethod 来进行调用的。 最后所有关于QML和c++交互部分就基本写完,如果想要更多的东西,或者一些其他方法,强烈看看 http://doc.qt.nokia.com/4.7-snapshot/qtbinding.html,或者帮助文档,(究竟是不是我的文档里面没有还是怎么的)

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值