void CommentDialog::on_button_smilely_clicked()
{
	QSelectFaceWidget* selectFace = new QSelectFaceWidget(Global::emotionPathTemp, this);
	selectFace->setStyleSheet("QLabel{color: #000000}QPushButton{background-color: transparent}");
	QPoint GlobalPoint(this->ui.button_smilely->mapToGlobal(QPoint(0, 0)));//获取控件在窗体中的坐标
	int y = GlobalPoint.y();
	selectFace->popUp(GlobalPoint, this->ui.button_smilely->height()+10);

	QObject::connect(selectFace, &QSelectFaceWidget::FaceSelected, [=](const QString &filename){
 		QString iconName = GetPicName(filename);
		QTextDocument *document =this->ui.TextEdit_commentText->document();
		QTextCursor cursor = this->ui.TextEdit_commentText->textCursor();
		QFileInfo fiPic(filename);
		if (fiPic.exists())
		{
			QImage image(filename);
			image = image.scaled(30, 30, Qt::KeepAspectRatio, Qt::SmoothTransformation);
			document->addResource(QTextDocument::ImageResource, QUrl(iconName), image);
			cursor.insertImage(iconName);
		}

		this->ui.TextEdit_commentText->setFocus();
		//this->ui.TextEdit_commentText->moveCursor(QTextCursor::NoMove);
	});
	

};
Esempio n. 2
0
void DocBlock::addLink(QUrl url)
{
    myTextItem->setTextInteractionFlags(Qt::TextSelectableByKeyboard);
    docType = Link;
    path = url.toString();
    QString str = path;

    // add file icon
    QTextCursor cursor = QTextCursor(myTextItem->document());
    QFileInfo info(url.toLocalFile());
    QFileIconProvider *provider = new QFileIconProvider();
    QImage image(provider->icon(info).pixmap(16, 16).toImage());
    cursor.document()->setPlainText(" ");
    cursor.insertImage(image);
	
    if (str.lastIndexOf("/") > -1)
        str = str.right(str.size() - str.lastIndexOf("/") - 1);

    QString html = "<a href=\""+path+"\">"+str+"</a>";
    cursor.insertHtml(html);
	
    if (arrow != 0) arrow->setColor(getHoverColor());

    updateBlock(false);
}
Esempio n. 3
0
void Format::parseBlock( QTextCursor &cursor, const QDomElement &element )
{
//  dbg() << "Format::parseBlock()" << endl;

  QDomNode n;
  for( n = element.firstChild(); !n.isNull(); n = n.nextSibling() ) {
    QDomElement e = n.toElement();
    if ( e.tagName() == "fragment" ) {
      QTextCharFormat format;
      if ( e.hasAttribute( "link" ) ) {
        format.setAnchor( true );
        QString href = e.attribute( "link" );
        format.setAnchorHref( href );
        format.setFontUnderline( true );
        if ( href.startsWith( "todoodle:" ) ) {
          format = TextFormats::topicLinkCharFormat( href );
        } else {
          format = TextFormats::hyperLinkCharFormat( href );
        }
      }
      if ( e.attribute( "bold" ) == "true" ) {
        format.setFontWeight( QFont::Bold );
      }
      if ( e.attribute( "italic" ) == "true" ) {
        format.setFontItalic( true );
      }
      int fontSize = 0;
      if ( e.hasAttribute( "fontsize" ) ) {
        fontSize = e.attribute( "fontsize" ).toInt();
      } else {
        fontSize = 10;
      }
      if ( fontSize > 0 ) format.setFontPointSize( fontSize );
      
      QDomNode n2;
      for( n2 = e.firstChild(); !n2.isNull(); n2 = n2.nextSibling() ) {
//        dbg() << "TICK" << endl;
        QDomText t = n2.toText();
        if ( !t.isNull() ) {
//          dbg() << "TEXT: '" << t.data() << "'" << endl;
          cursor.insertText( t.data(), format );
//          dbg() << "done" << endl;
        } else {
          QDomElement e2 = n2.toElement();
          if ( !e2.isNull() ) {
            if ( e2.tagName() == "todo" ) {
              QTextImageFormat f;
              if ( e2.attribute( "status" ) == "todo" ) {
                f.setName( ":/images/todo.png" );
              } else {
                f.setName( ":/images/tododone.png" );
              }
              cursor.insertImage( f );
            }
          }
        }
      }
    }
  }
}
Esempio n. 4
0
void CamlDevWindow::readCaml()
{
   
   QString stdOut = camlProcess->readAllStandardOutput();
   stdOut = removeUnusedLineBreaks(stdOut,false);
   if(drawTrees)
   {
      while(stdOut.indexOf("--LemonCamlCommand--") != -1)
      {
         int j = stdOut.indexOf("--LemonCamlCommand--"); //20
         int p = stdOut.indexOf("--EndLemonCamlCommand--"); //23
         if(p == -1)
         {
            appendOutput(tr("---LemonCaml error--- Unterminated command: not interpreted\n"), Qt::red);
            stdOut = stdOut.mid(j + 20);
         }
         else
         {
            appendOutput(stdOut.left(j),this->palette().color(QPalette::WindowText));
            QString cmd = stdOut.mid(j + 20, (p - j - 20));
            QStringList cmdlist = parseBlockCommand(cmd);

            processCommandList(&cmdlist);
            stdOut = stdOut.mid(p + 23);
         }
      }
      while(stdOut.indexOf("--LemonTree--") != -1) //TODO: change this!!!! never leave such an absolute type name here; ask the user, instead.
      {
         int j = stdOut.indexOf("--LemonTree--"); // 17
         int p = stdOut.indexOf("--EndLemonTree--"); //20
         if(p == -1)
         {
            appendOutput(tr("---LemonCaml error--- Unterminated tree: not drawn\n"), Qt::red);
            stdOut = stdOut.mid(j + 17);  
         }
         else
         {
            appendOutput(stdOut.left(j),this->palette().color(QPalette::WindowText));
            QString arb = stdOut.mid(j + 13, (p - j - 13));
            int k = arb.indexOf('(');
            if(k != -1)
            {
               QString arbString = arb.mid(k);
               treeParser* tp = new treeParser();
               QImage* img = tp->parseTree(arbString);
               QTextCursor cursor = outputZone->textCursor();
               cursor.insertImage((*img), QString(this->graphCount));
               outputZone->insertPlainText("\n");
               this->graphCount++;
            }
            stdOut = stdOut.mid(p + 16);
         }
         
      }
   }
   if(stdOut != "") appendOutput(stdOut,this->palette().color(QPalette::WindowText));
   
}
void FormattedTextWidget::addImageToDescription()
{
    QString filename = QFileDialog::getOpenFileName( this, tr( "Choose image" ), tr( "All Supported Files (*.png *.jpg *.jpeg)" )  );
    QImage image( filename );
    if( !image.isNull() ) {
        QTextCursor cursor = d->m_description->textCursor();
        cursor.insertImage( image, filename );
    }
}
Esempio n. 6
0
//! [1]
void TextEdit::insertFromMimeData( const QMimeData *source )
{
    if (source->hasImage())
    {
        QImage image = qvariant_cast<QImage>(source->imageData());
        QTextCursor cursor = this->textCursor();
        QTextDocument *document = this->document();
        document->addResource(QTextDocument::ImageResource, QUrl("image"), image);
        cursor.insertImage("image");
    }
}
Esempio n. 7
0
void 
BioWidget::insertWidget( QWidget* w ) 
{
    w->installEventFilter( this );
    m_widgetImageFormat.setObjectType( WidgetImageFormat );
    m_widgetImageFormat.setProperty( WidgetData, QVariant::fromValue<QWidget*>( w ) );
    m_widgetImageFormat.setName( w->objectName() );
    
    QTextCursor cursor = textCursor();
    cursor.insertImage( m_widgetImageFormat, QTextFrameFormat::FloatLeft );
    setTextCursor( cursor );
}
Esempio n. 8
0
void messages_widget::peerCaptchaRequest(const libed2k::net_identifier& np, const QString& hash, const QPixmap& pm)
{
    Q_UNUSED(hash);
    std::vector<USER>::iterator it = findUser(np);
    if ( it != users.end())
    {
        addSystemMessage(it->edit, tr("*** To avoid spam user is asking for captcha authentification. Please enter symbols on the picture below:\n"));
        
        QTextCursor cursor = it->edit->textCursor();
        cursor.insertImage(pm.toImage());
        it->edit->append("\n");
    }
}
Esempio n. 9
0
void FlatTextarea::insertEmoji(EmojiPtr emoji, QTextCursor c) {
	c.removeSelectedText();

	QPixmap img(App::emojiSingle(emoji, _st.font->height));
	QString url = qsl("emoji://e.") + QString::number(emojiKey(emoji), 16);
	document()->addResource(QTextDocument::ImageResource, QUrl(url), QVariant(img));
	QTextImageFormat imageFormat;
	imageFormat.setWidth(img.width() / cIntRetinaFactor());
	imageFormat.setHeight(img.height() / cIntRetinaFactor());
	imageFormat.setName(url);
	imageFormat.setVerticalAlignment(QTextCharFormat::AlignBaseline);
	c.insertImage(imageFormat);
}
Esempio n. 10
0
void DocBlock::addImage(const QImage &image, QString imagePath)
{
    myTextItem->setTextInteractionFlags(Qt::TextSelectableByKeyboard);
    docType = Image;
    QTextCursor cursor = QTextCursor(myTextItem->document());
    cursor.document()->setPlainText("");
    cursor.insertImage(image);
    path = imagePath;

    if (arrow != 0) arrow->setColor(getHoverColor());

    updateBlock(false);
}
Esempio n. 11
0
void FillCellHelper::insertDecoration( KDReports::ReportBuilder& builder, QTextDocument& textDoc )
{
    QImage img = qvariant_cast<QImage>( cellDecoration );
    if ( img.isNull() ) {
        img = qvariant_cast<QIcon>( cellDecoration ).pixmap( iconSize ).toImage();
    }
    if ( !img.isNull() ) {
        static int imageNumber = 0;
        const QString name = QString::fromLatin1( "cell-image%1.png" ).arg( ++imageNumber );
        textDoc.addResource( QTextDocument::ImageResource, QUrl( name ), img );
        builder.currentDocumentData().addResourceName( name );
        cellCursor.insertImage( name );
    }
}
Esempio n. 12
0
void MailViewer::displayAttachments(const MessageHeader& msg)
{   
#if 0 //code doesn't yet work
   QTextDocument* textDocument = ui->message_content->document();
   QImage image;
   int i = 1;
   foreach (const bts::bitchat::attachment& attachment, msg.attachments)
      {
      image.fromData(attachment.body.data());
      QUrl url(QString("attachment_image_%1").arg(i++));
      textDocument->addResource( QTextDocument::ImageResource, url, QVariant ( image ) );
      QTextCursor cursor = ui->message_content->textCursor();
      QTextImageFormat imageFormat;
      imageFormat.setWidth( image.width() );
      imageFormat.setHeight( image.height() );
      imageFormat.setName( url.toString() );
      cursor.insertImage(imageFormat);
      }
#endif
}
Esempio n. 13
0
void TextEdit::imageOpen()
{
	QString fn = QFileDialog::getOpenFileName(this, tr("Open File..."),
	QString(), tr("images (*.png *.bmp *.jpg *.jpeg);;All Files (*)"));
	if (!fn.isEmpty()) {
		QMimeData mimeData;
		mimeData.setImageData(QImage(fn));
		QTextCursor cursor = this->textEdit->textCursor();
		QTextDocument *document = this->textEdit->document();
		QString newfile, imageName;
		do {
			imageName = name + "/img_" + QTime::currentTime().toString("mmsszzz.") + fn.section(".",-1);
			newfile = path + imageName;
		} while(QFile::exists(newfile));
		QFile::copy(fn, newfile);
		document->addResource(QTextDocument::ImageResource, newfile, QImage(newfile));
		cursor.insertImage(imageName);
		listAddedImages<<newfile;
	}
}
Esempio n. 14
0
def canInsertFromMimeData(source):
if source.hasImage:
    return True
       else:
               return QTextEdit.canInsertFromMimeData(source)

//! [0]

//! [1]
                          void TextEdit::insertFromMimeData( const QMimeData *source )
    {
        if (source->hasImage())
        {
            QImage image = qvariant_cast<QImage>(source->imageData());
            QTextCursor cursor = this->textCursor();
            QTextDocument *document = this->document();
            document->addResource(QTextDocument::ImageResource, QUrl("image"), image);
            cursor.insertImage("image");
        }
    }
Esempio n. 15
0
void DocBlock::setFolded(bool fold)
{
    if (fold == folded) return; //! do nothing

    folded = fold;

    if (fold)
    {
        backup = myTextItem->document()->clone();

        if (docType == Image)
        {
            QTextCursor cursor = QTextCursor(myTextItem->document());
            cursor.document()->setPlainText(" ");
            cursor.insertImage(QImage(":/image.png"));
            cursor.insertText(QFileInfo(path).fileName());
        }
        else
        {
            QString cue = myTextItem->toPlainText();
            int index = cue.indexOf("\n");
            cue.truncate(qMin(8, index));
            cue.append(" ...");
            myTextItem->setPlainText(cue);
            myTextItem->setTextInteractionFlags(Qt::TextEditable | Qt::TextSelectableByKeyboard);
        }

    }
    else
    {
        Q_ASSERT(backup != 0);
        myTextItem->setDocument(backup);

        if (!docType == Text)
            myTextItem->setTextInteractionFlags(Qt::NoTextInteraction);

        backup = 0;
    }
    updateBlock();
}
Esempio n. 16
0
void MainWindow::on_insertImage_clicked()
{
    //get select image
    QString fn = QFileDialog::getOpenFileName(this, tr("插入图像"),
                                              QString(),
                                              tr("Joint Photographic Experts Group (*.jpg *.jpeg);;") +
                                              "Portable Network Graphics (*.png);;" +
                                              "Windows Bitmap (*.bmp);;" +
                                              "GIF (*.gif);;" +
                                              "Portable Bitmap (*.pbm);;" +
                                              "Portable Graymap (*.pgm);;" +
                                              "Portable Pixmap (*.ppm);;" +
                                              "X11 Bitmap (*.xbm);;" +
                                              "X11 Pixmap (*.xpm);;" +
                                              "Scalable Vector Graphics (*.svg);;" +
                                              "All Files (*)");

    if (fn.isEmpty())
        return;
    if (!(fn.endsWith(".jpg", Qt::CaseInsensitive)
          || fn.endsWith(".jpeg", Qt::CaseInsensitive)
          || fn.endsWith(".png", Qt::CaseInsensitive)
          || fn.endsWith(".gif", Qt::CaseInsensitive)
          || fn.endsWith(".pbm", Qt::CaseInsensitive)
          || fn.endsWith(".pgm", Qt::CaseInsensitive)
          || fn.endsWith(".ppm", Qt::CaseInsensitive)
          || fn.endsWith(".xbm", Qt::CaseInsensitive)
          || fn.endsWith(".xpm", Qt::CaseInsensitive)
          || fn.endsWith(".svg", Qt::CaseInsensitive))) {
        QMessageBox::warning(this, tr("自动出卷系统"), tr("不支持的文件格式。"));
        return;
    }

    QTextEdit *pEdit = textEditor.editor;
    QTextCursor cursor = pEdit->textCursor();
    QTextImageFormat imageFormat;
    imageFormat.setName(fn);
    //pEdit->setText();
    cursor.insertImage(imageFormat);
}
Esempio n. 17
0
void Matrix::exportRasterImage(const QString& fileName, int quality, int dpi)
{
	if (!dpi)
		dpi = logicalDpiX();

	QImage image = d_matrix_model->renderImage();
	int dpm = (int)ceil(100.0/2.54*dpi);
	image.setDotsPerMeterX(dpm);
	image.setDotsPerMeterY(dpm);
	if (fileName.endsWith(".odf")){
		QTextDocument *document = new QTextDocument();
		QTextCursor cursor = QTextCursor(document);
		cursor.movePosition(QTextCursor::End);
		cursor.insertText(objectName());
		cursor.insertBlock();
		cursor.insertImage(image);

		QTextDocumentWriter writer(fileName);
		writer.write(document);
	} else
		image.save(fileName, 0, quality);
}
Esempio n. 18
0
void DocBlock::addWebLink(QUrl url)
{
    myTextItem->setTextInteractionFlags(Qt::TextSelectableByKeyboard);
    docType = WebLink;

    // add web icon
    QTextCursor cursor = QTextCursor(myTextItem->document());
    cursor.document()->setPlainText(" ");
    cursor.insertImage(QImage(":/weblink.png"));

    path = url.toString();
    QString str = path;

    if (str.lastIndexOf("/") > 7)
        str = str.left(str.lastIndexOf("/"));

    QString html = "<a href=\""+path+"\">"+str+"</a>";
    cursor.insertHtml(html);

    if (arrow != 0)
        arrow->setColor(getHoverColor());

    updateBlock(false);
}
Esempio n. 19
0
// Вставка MIME данных
void EditorTextArea::insertFromMimeData(const QMimeData *source)
{
    QTextCursor cursor = this->textCursor();
    QTextDocument *document = this->document();

// Вставка картинки
    if(source->hasImage())
    {
        QImage image=qvariant_cast<QImage>(source->imageData());

        // Картинка будет хранится в ресурсах во внутреннем формате
        // без потери качества, поэтому затем при записи
        // легко сохраняется в PNG формат. Чтобы избежать путаницы,
        // сразу имя ресурса картинки задается как PNG файл
        QString imageName="image"+QString::number(rand())+".png";

        document->addResource(QTextDocument::ImageResource, QUrl(imageName), image);
        cursor.insertImage(imageName);
        return;
    }

    if(source->hasHtml())
    {
        QString html=qvariant_cast<QString>(source->html());
        cursor.insertHtml(html);
        return;
    }

    if(source->hasText())
    {
        QString text=qvariant_cast<QString>(source->text());
        cursor.insertText(text);
        return;
    }

}
Esempio n. 20
0
void ChatView::appendMessage(QString message, QString sender, UserLevelFlags userLevel, bool playerBold)
{
	bool atBottom = verticalScrollBar()->value() >= verticalScrollBar()->maximum();
	bool sameSender = (sender == lastSender) && !lastSender.isEmpty();
	QTextCursor cursor = prepareBlock(sameSender);
	lastSender = sender;
	
	if (showTimestamps && !sameSender) {
		QTextCharFormat timeFormat;
		timeFormat.setForeground(Qt::black);
		cursor.setCharFormat(timeFormat);
		cursor.insertText(QDateTime::currentDateTime().toString("[hh:mm] "));
	}
	
	QTextCharFormat senderFormat;
	if (tabSupervisor && tabSupervisor->getUserInfo() && (sender == QString::fromStdString(tabSupervisor->getUserInfo()->name()))) {
		senderFormat.setFontWeight(QFont::Bold);
		senderFormat.setForeground(Qt::red);
	} else {
		senderFormat.setForeground(Qt::blue);
		if (playerBold)
			senderFormat.setFontWeight(QFont::Bold);
	}
	senderFormat.setAnchor(true);
	senderFormat.setAnchorHref("user://" + QString::number(userLevel) + "_" + sender);
	if (!sameSender) {
		if (!sender.isEmpty()) {
			const int pixelSize = QFontInfo(cursor.charFormat().font()).pixelSize();
			cursor.insertImage(UserLevelPixmapGenerator::generatePixmap(pixelSize, userLevel).toImage(), QString::number(pixelSize) + "_" + QString::number((int) userLevel));
			cursor.insertText(" ");
		}
		cursor.setCharFormat(senderFormat);
		if (!sender.isEmpty())
			sender.append(": ");
		cursor.insertText(sender);
	} else
		cursor.insertText("    ");
	
	QTextCharFormat messageFormat;
	if (sender.isEmpty())
		messageFormat.setForeground(Qt::darkGreen);
	cursor.setCharFormat(messageFormat);
	
	int from = 0, index = 0;
	while ((index = message.indexOf('[', from)) != -1) {
		cursor.insertText(message.left(index));
		message = message.mid(index);
		if (message.isEmpty())
			break;
		
		if (message.startsWith("[card]")) {
			message = message.mid(6);
			int closeTagIndex = message.indexOf("[/card]");
			QString cardName = message.left(closeTagIndex);
			if (closeTagIndex == -1)
				message.clear();
			else
				message = message.mid(closeTagIndex + 7);
			
			QTextCharFormat tempFormat = messageFormat;
			tempFormat.setForeground(Qt::blue);
			tempFormat.setAnchor(true);
			tempFormat.setAnchorHref("card://" + cardName);
			
			cursor.setCharFormat(tempFormat);
			cursor.insertText(cardName);
			cursor.setCharFormat(messageFormat);
		} else if (message.startsWith("[url]")) {
			message = message.mid(5);
			int closeTagIndex = message.indexOf("[/url]");
			QString url = message.left(closeTagIndex);
			if (closeTagIndex == -1)
				message.clear();
			else
				message = message.mid(closeTagIndex + 6);
			
			if (!url.contains("://"))
				url.prepend("http://");
			
			QTextCharFormat tempFormat = messageFormat;
			tempFormat.setForeground(Qt::blue);
			tempFormat.setAnchor(true);
			tempFormat.setAnchorHref(url);
			
			cursor.setCharFormat(tempFormat);
			cursor.insertText(url);
			cursor.setCharFormat(messageFormat);
		} else
			from = 1;
	}
	if (!message.isEmpty())
		cursor.insertText(message);
	
	if (atBottom)
		verticalScrollBar()->setValue(verticalScrollBar()->maximum());
}
Esempio n. 21
0
bool OpenDocument::traite_image(QTextCursor &curseur, QDomElement e, QString nom){
    ErrorManager instance_erreur;
    QString file = "";

    if(e.tagName() != "draw:image"){
        instance_erreur.Erreur_msg(tr("ODT : Mauvais paramètre envoyé : fonction de lecture d'image"), QMessageBox::Ignore);
        return false;
    }

    //On détecte si elle est en local ou en HTTP
    if(e.attribute("xlink:href").contains("http")){//Internet
        //On va piocher l'image sur Internet

        //On nettoye l'URL
        QString url_temp = e.attribute("xlink:href");
        if(url_temp.indexOf("?", 0) > 0){
            //Il y en a -> on vire tout ce qui est après
            int pos_depart = url_temp.indexOf("?", 0); int fin = url_temp.size();
            url_temp = url_temp.remove(pos_depart, fin);
        }
        QUrl url_image(url_temp);
        if(!url_image.isValid()){
            instance_erreur.Erreur_msg(tr("ODT : Erreur lors du téléchargement d'éléments distants"), QMessageBox::Ignore);
            return false;
        }

        QNetworkAccessManager nw_manager;
        QNetworkRequest request(url_image);
        QNetworkReply *reponse = nw_manager.get(request);
        QEventLoop eventLoop;
        QObject::connect(reponse, SIGNAL(finished()), &eventLoop, SLOT(quit()));
        eventLoop.exec();
        QImage image;
        image.loadFromData(reponse->readAll());
        QString ext = url_image.toString();
        ext = ext.remove(0, (ext.size()-4));
        qsrand(QDateTime::currentDateTime ().toTime_t ());
        file = QDir::tempPath()+QDir::separator()+QString::number(qrand())+".png";
        if(!image.isNull()){
            if(!image.save(file, "PNG")){
                //!sauvegarde
                instance_erreur.Erreur_msg(tr("ODT : Sauvegarde échouée de l'image téléchargée"), QMessageBox::Ignore);
                return false;
            }
        }
        else{
            //Image nulle
            instance_erreur.Erreur_msg(tr("ODT : Téléchargement échoué d'une image"), QMessageBox::Ignore);
            return false;
        }

        delete reponse;
    }
    else if(e.attribute("xlink:href").contains("Pictures")){//Local
        //On extrait le fichier
        QZipReader image(nom_odt, QIODevice::ReadOnly);
        Outils instance_outils;
        QString clean_fichier = e.attribute("xlink:href");
        clean_fichier = clean_fichier.split("/").last();
        image.extractOne(QDir::tempPath(), clean_fichier);
        image.close();

        //On sélectionne le fichier
        file = QDir::tempPath()+QDir::separator()+clean_fichier;

    }
    else{ //C'est pas normal ça : on se casse
        instance_erreur.Erreur_msg(tr("ODT : source d'image non trouvée"), QMessageBox::Ignore);
        return false;
    }


    //On affiche l'image
    QTextImageFormat format_image;
    format_image = cree_image_format(nom);
    format_image.setName(file);
    //On récupère d'éventuelles spécifications de taille
    QDomNode enfants = e.parentNode();
    e = enfants.toElement();
    //Width de l'image
    if(e.hasAttribute("svg:width")){
        QString width = e.attribute("svg:width");
        double value = width.left(width.length() - 2).toDouble();
        format_image.setWidth(value*28.3465058);
    }
    //Height de l'image
    if(e.hasAttribute("svg:height")){
        QString height = e.attribute("svg:height");
        double value = height.left(height.length() - 2).toDouble();
        format_image.setHeight(value*28.34650058);
    }

    QTextBlockFormat format_block_image;
    format_block_image = cree_bloc_format2(nom);
    curseur.insertBlock();
    curseur.movePosition(QTextCursor::PreviousBlock);
    curseur.setBlockFormat(format_block_image);
    curseur.insertImage(format_image);
    curseur.movePosition(QTextCursor::End);

    return true;
}
Esempio n. 22
0
void ChatView::appendMessage(QString message, RoomMessageTypeFlags messageType, QString sender, UserLevelFlags userLevel, QString UserPrivLevel, bool playerBold)
{
    bool atBottom = verticalScrollBar()->value() >= verticalScrollBar()->maximum();
    bool sameSender = (sender == lastSender) && !lastSender.isEmpty();
    QTextCursor cursor = prepareBlock(sameSender);
    lastSender = sender;
    
    // timestamp
    if (showTimestamps && (!sameSender || sender.toLower() == "servatrice") && !sender.isEmpty()) {
        QTextCharFormat timeFormat;
        timeFormat.setForeground(QColor(SERVER_MESSAGE_COLOR));
        if (sender.isEmpty())
            timeFormat.setFontWeight(QFont::Bold);
        cursor.setCharFormat(timeFormat);
        cursor.insertText(QDateTime::currentDateTime().toString("[hh:mm:ss] "));
    }

    // nickname
    if (sender.toLower() != "servatrice") {
        QTextCharFormat senderFormat;
        if (tabSupervisor && tabSupervisor->getUserInfo() &&
            (sender == QString::fromStdString(tabSupervisor->getUserInfo()->name()))) {
            senderFormat.setForeground(QBrush(getCustomMentionColor()));
            senderFormat.setFontWeight(QFont::Bold);
        } else {
            senderFormat.setForeground(QBrush(OTHER_USER_COLOR));
            if (playerBold)
                senderFormat.setFontWeight(QFont::Bold);
        }
        senderFormat.setAnchor(true);
        senderFormat.setAnchorHref("user://" + QString::number(userLevel) + "_" + sender);
        if (sameSender) {
            cursor.insertText("    ");
        } else {
            if (!sender.isEmpty() && tabSupervisor->getUserListsTab()) {
                const int pixelSize = QFontInfo(cursor.charFormat().font()).pixelSize();
                QMap<QString, UserListTWI *> buddyList = tabSupervisor->getUserListsTab()->getBuddyList()->getUsers();
                cursor.insertImage(UserLevelPixmapGenerator::generatePixmap(pixelSize, userLevel, buddyList.contains(sender), UserPrivLevel).toImage());
                cursor.insertText(" ");
            }
            cursor.setCharFormat(senderFormat);
            if (!sender.isEmpty())
                sender.append(": ");
            cursor.insertText(sender);
        }
    }

    // use different color for server messages 
    defaultFormat = QTextCharFormat();
    if (sender.isEmpty()) {
        switch (messageType) {
            case Event_RoomSay::Welcome:
                defaultFormat.setForeground(Qt::darkGreen);
                defaultFormat.setFontWeight(QFont::Bold);
                break;
            case Event_RoomSay::ChatHistory:
                defaultFormat.setForeground(Qt::gray);
                defaultFormat.setFontWeight(QFont::Light);
                defaultFormat.setFontItalic(true);
                break;
            default:
                defaultFormat.setForeground(Qt::darkGreen);
                defaultFormat.setFontWeight(QFont::Bold);
        }
    } else if (sender.toLower() == "servatrice") {
        defaultFormat.setForeground(Qt::darkGreen);
        defaultFormat.setFontWeight(QFont::Bold);
    }
    cursor.setCharFormat(defaultFormat);

    bool mentionEnabled = settingsCache->getChatMention();
    highlightedWords = settingsCache->getHighlightWords().split(' ', QString::SkipEmptyParts);

    // parse the message
    while (message.size())
    {
        QChar c = message.at(0);    
        switch(c.toLatin1())
        {
            case '[':
                checkTag(cursor, message);
                break;
            case '@':
                if(mentionEnabled) {
                    checkMention(cursor, message, sender, userLevel);
                } else {
                    cursor.insertText(c, defaultFormat);
                    message = message.mid(1);
                }
                break;
            case ' ':
                cursor.insertText(c, defaultFormat);
                message = message.mid(1);
                break;
            default:
                if(c.isLetterOrNumber()) {
                    checkWord(cursor, message);
                } else {
                    cursor.insertText(c, defaultFormat);
                    message = message.mid(1);
                }
                break;
        }
    }

    if (atBottom)
        verticalScrollBar()->setValue(verticalScrollBar()->maximum());
}
Esempio n. 23
0
void ContactListEdit::addContactEntry(const QString& contactText, const bts::addressbook::contact& c)
  {
  QFont        default_font;
  default_font.setPointSize( default_font.pointSize() - 1 );
  QFontMetrics font_metrics(default_font);
  QRect        bounding = font_metrics.boundingRect(contactText);
  int          completion_width = font_metrics.width(contactText);
  int          completion_height = bounding.height();

  completion_width += 20;

  QImage   completion_image(completion_width, completion_height + 4, QImage::Format_ARGB32);
  completion_image.fill(QColor(0, 0, 0, 0) );
  QPainter painter;
  painter.begin(&completion_image);
  painter.setFont(default_font);
  painter.setRenderHint(QPainter::Antialiasing);

  QBrush brush(Qt::SolidPattern);
  brush.setColor( QColor( 205, 220, 241 ) );
  QPen  pen;

  bool isKeyhoteeFounder = Contact::isKeyhoteeFounder(c);

  if (isKeyhoteeFounder)
    {
    QLinearGradient grad(QPointF(0, 0), QPointF(0, 1));
    grad.setCoordinateMode(QGradient::ObjectBoundingMode);
    grad.setColorAt(0, QColor(35, 40, 3));
    grad.setColorAt(0.102273, QColor(136, 106, 22));
    grad.setColorAt(0.225, QColor(166, 140, 41));
    grad.setColorAt(0.285, QColor(204, 181, 74));
    grad.setColorAt(0.345, QColor(235, 219, 102));
    grad.setColorAt(0.415, QColor(245, 236, 112));
    grad.setColorAt(0.52, QColor(209, 190, 76));
    grad.setColorAt(0.57, QColor(187, 156, 51));
    grad.setColorAt(0.635, QColor(168, 142, 42));
    grad.setColorAt(0.695, QColor(202, 174, 68));
    grad.setColorAt(0.75, QColor(218, 202, 86));
    grad.setColorAt(0.815, QColor(208, 187, 73));
    grad.setColorAt(0.88, QColor(187, 156, 51));
    grad.setColorAt(0.935, QColor(137, 108, 26));
    grad.setColorAt(1, QColor(35, 40, 3));

    brush = QBrush(grad);
    pen.setColor( QColor( 103, 51, 1 ) );
    }
  else
    {
    brush.setColor( QColor( 205, 220, 241 ) );
    pen.setColor( QColor( 105,110,180 ) );
    }

  painter.setBrush(brush);
  painter.setPen(pen);
  painter.drawRoundedRect(0, 0, completion_width - 1, completion_image.height() - 1, 8, 8,
    Qt::AbsoluteSize);
  painter.setPen(QPen());
  painter.drawText(QPoint(10, completion_height - 2), contactText);

  QTextDocument* doc = document();
  doc->addResource(QTextDocument::ImageResource, QUrl(contactText), completion_image);
  QTextImageFormat format;
  format.setName(contactText);

  encodePublicKey(c.public_key, &format);

  QTextCursor txtCursor = textCursor();
  txtCursor.insertImage(format);

  txtCursor.insertText(" ");
  setTextCursor(txtCursor);
  }
Esempio n. 24
0
void MainWindow::formatQuestions(const PACKEDQUESTIONS &qset)
{

    TestAssistance *pt = TestAssistance::get();
    QTextEdit *pEdit = textEditor.editor;
    QTextCursor cursor = pEdit->textCursor();

    //set alignment center
    pEdit->setAlignment(Qt::AlignHCenter);
    groupCheck(0);

    //set font of title and info
    QFont font = pEdit->font();
    QTextCharFormat fmt;
    font.setBold(true);
    font.setPointSize(14);
    fmt.setFont(font);
    cursor.select(QTextCursor::BlockUnderCursor);
    cursor.mergeCharFormat(fmt);

    //insert school name
    cursor.insertText(tr("%1\n").arg(pt->getPaperInfo().strSchool));

    //insert title
    cursor.insertText(tr("“%1”专业(学院) 2011—2012学年第一学期\n").arg(pt->getPaperInfo().major));


    //insert paper info
    cursor.insertText(tr("《%1》期末考试试卷(%2卷) 考核形式(%3卷)\n").arg(pt->getPaperInfo().strCourse)
                      .arg(pt->getPaperInfo().strPaperType).arg(((pt->getPaperInfo().bOpenOrClose)?"开":"闭")));

    //insert author
    cursor.insertText(tr("作者:%1\n").arg(pt->getPaperInfo().strAuthor));

    pEdit->setTextCursor(cursor);

    //set alignment left
    pEdit->setAlignment(Qt::AlignLeft);
    groupCheck(2);

    //get judge
    QString text;
    int type = 0;

    const std::vector<QUESTION> &j = qset.judge;
    if(!j.empty()){
        insertQuestionTypeTitle(tr("%1.判断题").arg(digitToChinese(type+1)));
        type++;

        for(size_t i = 0; i != j.size(); ++i){
            cursor.insertText(tr("%1.").arg(i+1) + j[i].txt + "\n");
            if(!j[i].imgBytes.isEmpty()){
                QImage img;
                img.loadFromData(j[i].imgBytes, "PNG");
                cursor.insertImage(img);
                cursor.insertText("\n\n");
            }
            pEdit->setTextCursor(cursor);
        }
    }

    //get choice
    text.clear();
    const std::vector<QUESTION> &c = qset.choice;
    if(!c.empty()){
        insertQuestionTypeTitle(tr("%1.选择题").arg(digitToChinese(type+1)));
        type++;

        for(size_t i = 0; i != c.size(); ++i){
            cursor.insertText(tr("%1.").arg(i+1) + c[i].txt + "\n");
            if(!c[i].imgBytes.isEmpty()){
                QImage img;
                img.loadFromData(c[i].imgBytes, "PNG");
                cursor.insertImage(img);
                cursor.insertText("\n\n");
            }
            else
                cursor.insertText("\n");
            pEdit->setTextCursor(cursor);
        }
    }

    //get fill
    text.clear();
    const std::vector<QUESTION> &f = qset.fill;
    if(!f.empty()){
        insertQuestionTypeTitle(tr("%1.填空题").arg(digitToChinese(type+1)));
        type++;

        for(size_t i = 0; i != f.size(); ++i){
            cursor.insertText(tr("%1.").arg(i+1) + f[i].txt + "\n");
            if(!f[i].imgBytes.isEmpty()){
                QImage img;
                img.loadFromData(f[i].imgBytes, "PNG");
                cursor.insertImage(img);
                cursor.insertText("\n\n");
            }
            pEdit->setTextCursor(cursor);
        }
    }

    //get calc
    text.clear();
    const std::vector<QUESTION> &l = qset.calc;
    if(!l.empty()){
        insertQuestionTypeTitle(tr("%1.计算题").arg(digitToChinese(type+1)));
        type++;

        for(size_t i = 0; i != l.size(); ++i){
            cursor.insertText(tr("%1.").arg(i+1) + l[i].txt + "\n");
            if(!l[i].imgBytes.isEmpty()){
                QImage img;
                img.loadFromData(l[i].imgBytes, "PNG");
                cursor.insertImage(img);
                cursor.insertText("\n\n");
            }
            pEdit->setTextCursor(cursor);
        }
    }

    //get ans
    text.clear();
    const std::vector<QUESTION> &a = qset.ans;
    if(!a.empty()){
        insertQuestionTypeTitle(tr("%1.问答题").arg(digitToChinese(type+1)));
        type++;

        for(size_t i = 0; i != a.size(); ++i){
            cursor.insertText(tr("%1.").arg(i+1) + a[i].txt + "\n");
            if(!a[i].imgBytes.isEmpty()){
                QImage img;
                img.loadFromData(a[i].imgBytes, "PNG");
                cursor.insertImage(img);
                cursor.insertText("\n\n");
            }
            else
                cursor.insertText("\n");
            pEdit->setTextCursor(cursor);
        }
    }
}