2012-03-19 1 views
3

QT 응용 프로그램을 사용하여 테이블을 만들고이 테이블을 클립 보드에 복사하여 테이블로 libreoffice에 붙여 넣을 수 있어야합니다. 작가 또는 MS 워드 나중에. 내 첫 번째 방법QT를 통해 클립 보드에 (rtf) 테이블 복사 (또는 : 클립 보드에 QTextDocument 쓰기)

테이블에 대한 HTML 코드를 작성하고

QClipboard *clipboard = QApplication::clipboard(); 
QMimeData *mimeData = new QMimeData(); 
mimeData->setData("text/html", html.toUtf8()); 
clipboard->setMimeData(mimeData, QClipboard::Clipboard); 

이러한 접근 방식은 작동하지 않았다으로 클립 보드에 삽입하는 것이 었습니다. 붙여 넣을 때 표 셀은 서로 추가되고 서식없이 삽입됩니다.

내 두 번째 방법 사용하여 RTF :

QTextDocument rtfDocument; 
rtfDocument.setHtml(html); 

하지만 클립 보드에이 QTextDocument를 복사 할 수있는 방법을 찾을 수 없습니다. 있어요? 나는 QTextDocument 밖으로 RTF 코드를 얻을 수 있다면, 나는

QClipboard *clipboard = QApplication::clipboard(); 
QMimeData *mimeData = new QMimeData(); 
mimeData->setData("text/rtf", rtfDocument.getCode()); 
clipboard->setMimeData(mimeData, QClipboard::Clipboard); 

같은 방법을 사용할 수 있습니다 그러나 나는 또한 RTF 코드를 반환하는 함수를 찾지 못했습니다.

편집 : 나는 클립 보드에 RTF 코드를 복사하는 작업 방법이 위의 마지막 코드 상자

. 그래서 테이블을 나타내는 RTF 코드를 생성 할 수있는 모든 솔루션이 내 문제를 해결할 것입니다.

+0

을 설정 http://stackoverflow.com/questions/294343/read-and -write-rtf-files-with-c-qt)하면 [librtf] (http://sourceforge.net/projects/librtf/)에서 RTF 처리를 할 수 있습니다. 나는 그것에 대해 조사 할 것이다. – Attila

+0

Unfortunatelly librtf는 구문 분석 만 허용하고 rtf 파일은 만들지 않습니다. – Heinzi

답변

2

당신 수 QTextDocument::toHtml()를 사용하여 시도하고 ([이 SO 질문]에 대한 답변에 따르면, 마임 유형을 text/html로

+0

이것이 첫 번째 접근 방식 이었지만 작동하지 않았습니다 (자세한 내용은 질문 참조). 나는 혼자서 html 코드를 작성했으나 문제가되어서는 안된다. 파이어 폭스에서 테이블을 LO 작성자로 복사 할 때도 잘못된 결과가 나타납니다. 나는 LO 작가가 HTML 태그를 무시한다고 생각한다. – Heinzi

+0

나는 그것을 작동시켰다. Libreoffice는 html 태그를 무시 했으므로 html 태그를 무시했습니다. – Heinzi

0

나는 gedit 1[tab space]2[tab space]3\n4[tab space]5[tab space]6에 쓴 다음 스프레드 시트에 복사하여 사용했습니다. 그래서, "\ t"를 사용하여 행의 셀을 분리하고 "\ n"을 사용하여 행을 분리하면 작동합니다.

+0

Excel/Calc가 아닌 MS Word/LO Writer에서 테이블이 필요합니다. 그래서 저는 rtf와 같은 형식이 필요하다고 생각합니다. 불분명 한 질문에 대해 유감스럽게 생각합니다.이를 더 명확하게 변경했습니다. – Heinzi

3

데이터 소스가 무엇인지 확실하지 않지만 여기서는 보통 QTableView의 하위 클래스를 사용하여 복사 가능하도록 만든 코드입니다. 일부 코드가 잘려나 갔지만 기본 아이디어를 얻을 수 있습니다. RTF/HTML은 잔인합니다. 모든 스프레드 시트는 좋은 CSV를 수용합니다.

물론이 답변은 포맷팅이 필요하다면 전혀 도움이되지 않습니다. 그것이 요구 사항인지 아닌지에 대해서는 귀하의 질문에서 분명하지 않았습니다.

// Escapes a string according to RFC-4180 specification. 
static QString csvEscape(const QString &value) { 
    if (value.contains(QRegExp(QLatin1String("[\"\\n\\r,]")))) { 
    QString escaped(value); 
    escaped.replace(QLatin1String("\""), QLatin1String("\"\"")); 
    return QString::fromLatin1("\"%1\"").arg(escaped); 
    } else { 
    return value; 
    } 
} 

void ClipboardAwareTableView::Copy() const { 
    QModelIndexList indexes = selectedIndexes(); 

    Q_ASSERT(!indexes.isEmpty()); 
    if(indexes.isEmpty()) { 
    return; 
    } 

    // The default sort is by rows then columns. This is what we want. 
    qSort(indexes); 

    // Remember the mapping between model columns and visible columns. This is 
    // local instead of an instance member because it would need to be invalidated 
    // any time a column is added, removed, or moved. The minor performance hit 
    // is worth the simplicity. 
    QHash<int, int> map_cache; 

    // Before we start exporting text, we have to know the index of the left- 
    // most column in our selection range so we can add the appropriate number 
    // of column separators. 
    int minimum_column = GetViewColumnIndex(indexes.first().column(), &map_cache); 
    for (int i = 1; i < indexes.size(); ++i) { 
    minimum_column = 
     qMin(minimum_column, 
      GetViewColumnIndex(indexes.at(i).column(), &map_cache)); 
    } 

    // Keep track of the previous index so that we know if we need a new line and 
    // how many column separators to insert. We start with an invalid index. 
    QModelIndex previous; 

    QString text; 

    for (int i = 0; i < indexes.size(); ++i) { 
    QModelIndex current = indexes.at(i); 

    // Do we need to add a new line character? 
    if (previous.isValid() && current.row() != previous.row()) { 
     text.append(QLatin1String("\n")); 
    } 

    // Are we on a new line? 
    if (!previous.isValid() || current.row() != previous.row()) { 
     // Add enough separators to get from the minimum to the current column. 
     text.append(QString::fromLatin1(",") 
        .repeated(GetViewColumnIndex(current.column(), &map_cache) - 
          minimum_column)); 
    } else { 
     // Add enough separators to get from the previous to the current column. 
     text.append(QString::fromLatin1(",") 
        .repeated(GetViewColumnIndex(current.column(), &map_cache) - 
          GetViewColumnIndex(previous.column(), &map_cache))); 
    } 

    // Append the text. If the column delegate is a QStyledItemDelegate, we use 
    // the display text. 
    QStyledItemDelegate *delegate = 
     qobject_cast<QStyledItemDelegate*>(
      itemDelegateForColumn(current.column())); 
    if (delegate) { 
     text.append(csvEscape(delegate->displayText(current.data(), QLocale()))); 
    } else { 
     text.append(csvEscape(current.data().toString())); 
    } 

    previous = current; 
    } 

    qApp->clipboard()->setText(text); 
} 

int ClipboardAwareTableView::GetViewColumnIndex(
    int model_column_index, 
    QHash<int, int> *cached_mappings) const { 
    if (cached_mappings->contains(model_column_index)) { 
    return cached_mappings->value(model_column_index); 
    } 

    int view_index = 0; 
    for (int i = 0; i < model()->columnCount(); ++i) { 
    if (model_column_index == i) { 
     cached_mappings->insert(model_column_index, view_index); 
     return view_index; 
    } else if (!isColumnHidden(i)) { 
     ++view_index; 
    } 
    } 

    throw std::invalid_argument("model_column_index was out of range."); 
} 

void ClipboardAwareTableView::keyPressEvent(QKeyEvent *event) { 
    if (event->matches(QKeySequence::Copy) && !selectedIndexes().isEmpty()) { 
    Copy(); 
    event->accept(); 
    return; // The base class implementation will overwrite the clipboard. 
    } 

    event->ignore(); 
    QTableView::keyPressEvent(event); 
} 
+0

Excel/Calc가 아닌 MS Word/LO Writer에서 테이블이 필요합니다. 그래서 저는 rtf와 같은 형식이 필요하다고 생각합니다. 불분명 한 질문에 대해 유감스럽게 생각합니다.이를 더 명확하게 변경했습니다. – Heinzi

관련 문제