Заполнение шаблона word qt

Обновлено: 04.07.2024

Использование QTableWidget будет первым способом, который посоветуют Вам для создания таблиц с чекбоксами на Qt. Поэтому давайте рассмотрим и этот вариант работы с таблицами в Qt и конечно же применим чекбоксы.

Итак, чтобы урок был более приближен к реальности, захватим немного программного кода из урока по QDataWidgetMapper . А именно возьмём класс для работы с базой данных, чтобы уж сразу делать таблицу из базы данных. После чего сделаем форму главного окна приложения и выведем данные из таблицы с отображением чекбоксов. Естественно, при включении приложения таблица база данных будет создана и заполнена несколькими записями, которые мы и будем выводить в виджет.

Программный код был написан в QtCreator 3.3.1 на основе Qt 5.4.1.

  1. 1. Структура проекта для QTableWidget
  2. 2. mainwindow.ui
  3. 3. mainwindow.h
  4. 4. mainwindow.cpp
  5. 5. database.h
  6. 6. database.cpp
  7. 7. Итог

Структура проекта для QTableWidget

Предлагаю ознакомиться со структурой проекта:

  • QTableWidgetExample.pro - профайл;
  • mainwindow.h - заголовочный файл основного окна приложения;
  • mainwindow.cpp - исходный код окна;
  • main.cpp - основной исходный файл, с которого стартует приложение;
  • mainwindow.ui - формочка основного окна приложения;
  • database.h - заголовочный файл вспомогательного класса, применяющегося для работы с информацией, которая помещена в базу данных;
  • database.cpp - исходный файл вспомогательного класса, применяющегося для работы с информацией, которая помещена в базу данных;

mainwindow.ui

Всё, что Вам нужно сделать с этим файлом, это кинуть в форму главного окна в дизайнере QTableWidget.

mainwindow.h

В данном файле объявляется объект базы данных, с которым мы будем работать, а также метод для заполнения данными QTableWidget.

mainwindow.cpp

В этом файле заключена цель всего урока, а именно настройка QTableWidget и заполнение его записями из базы данных.

database.h

Данный файл отличается от того, что был взят из урока по QDataWidgetMapper тем, что была добавлена define директива для чекбокса, соответственно это повлекло изменение методов в файле database.cpp . А именно insertIntoDeviceTable и createDeviceTable .

database.cpp

В результате при запуске программы будет создано приложение, в котором будет таблица с четырьмя записями, две из которых будут с отмеченными чекбоксами.

Репутация: 0

Добрый день. Не могу найти инструментарий для работы с вордом. Кто что может посоветовать?



Просмотр профиля

Репутация: 23

shamanix,
смотря что хочешь деалть с word через qt.
можно что то делать через QAxObject
ссылка



Просмотр профиля

Репутация: 0

shamanix,
смотря что хочешь деалть с word через qt.
можно что то делать через QAxObject
ссылка
тупо писать текст и немного его форматировать,ничего более сложного. спасибо, погляжу



Просмотр профиля

Репутация: 94

А если необходимо с вордом работать в линуксе? Чо делать? Ведь ActiveQt "Windows only"



Просмотр профиля

Репутация: 0

А если необходимо с вордом работать в линуксе? Чо делать? Ведь ActiveQt "Windows only"

Придется использовать сторонние библиотеки. Может тут что-то найдется подходящее.


This page discusses various available options for working with Microsoft Word documents in your Qt application. Please also read the general considerations outlined on the Handling Document Formats page.

of completeness or correctness. In particular, use your own research and judgment when evaluating third-party libraries or tools!

One needs to distinguish between two different formats (this page deals with both of them):

Legacy "Word Document" format "Office Open XML Document" format
classification: binary XML-based
main filename extension: .doc .docx
main internet media type: application/vnd.ms-word application/vnd.openxmlformats-officedocument.wordprocessingml.document
default format of Word: until Word 2003 since Word 2007

Reading / Writing

Using Word itself

If you are exclusively targeting the Windows platform and Microsoft Word will be installed on all target machines, then you can use Qt’s ActiveX framework to access Word’s .doc and .docx processing functionality through OLE automation. For an introductory code example (and a way to list the API provided by Word's COM object), consult this how to (focuses on Microsoft Excel, but it works the same way for Word).

DLL file name COM object name platforms license
Microsoft Word ? Word.Application Windows commercial

Using independent parser/writer libraries

API .doc .docx reading writing platforms license
wv C yes no yes no Win, Mac, Linux GPL [strong copyleft]

Using manual XML processing

Files using the XML-based (.docx) format could be processed using Qt's XML handling classes (see Handling Document Formats).

TODO: Expand this section.

Using batch conversion tools

I opened the fileout and it says that the file has been corrupted.
Is there any other way to read and write docx files in Qt ?

Hi and welcome to devnet,

You are trying to read a binary file as text and then write that text again and it will be again read as binary. That wont work.

If you just want to copy the file, why not use one of QFile::copy overloads ?

@SGaist Actually I'm copying multiple files and put it into one. Is there any way I can do that ?


@Dante-Pham You want to combine multiple docx files into one? It is not possible with Qt. It will for sure not work if you just append them, even not in binary mode. You either need a library which understands docx format or you need to write docx parser by yourself.

@jsulm Do you know any other platform like Qt that can read and write multiple docx files like what i mentioned ?


@Dante-Pham No I don't. Maybe Microsoft provides something? It is their format. And you can take a look at LibreOffice - it can read/write docx.

@Dante-Pham
Hi. Even with DocX you will need to understand the actual structure of the document and
merge it by hand adding text to the target doc.
There is no tool i have ever seen that can BINARY merge word docs. (only in very old times)
Also note that DocX only goes to word 2007. Not newer. ( or docs not updated)
But DocX seems very high level.

Can I ask why you want to merge them ?
Also is it a requirement that your app can do it when no Office installed?

@mrjj Basically I'm trying to make a program that can copy lots of small documents and put it into just one file. It's like you have multiple questions and you merge them into just one test.
Office should always be installed with this program ( except for when it has already been installed )

Ok. i see.
Would it be option to do it via pdf or must end result be a doc?

@mrjj Input and Output should be .doc or .docx so that it will be easier for users to modify the files. Changing .doc to .pdf and vice versa is good but doesn't help very much because the core features I intend to implement will, in most cases, involve in working with .doc and .docx

@Dante-Pham
Ok. well DocX or something like it seems the way to go then.

There is also the option of a pure VBA project. But the widgets you
get there is not as advanced as Qt versions but the merging of docs would
be easy.

@mrjj After doing some research I think DocX may just work. However, I have never had any exprience dealing with .dll files, let alone using it in Qt. Do you have any suggestions on how to use it ?

Hallo, I think to understand the binary docx structrue is a very hard stuff.
Much more easy it would be to use the AcxtiveX interface for word.
Code something like this:

Open Doc1, select all text, copy to clipboard, close Doc1
open Doc2, set cursor to the end of the document, paste text, save doc2.

The AciteveX interface of Qt is very good and I have much experiences with it. I use it for Excel (fill Tables) and for Access (open Report an export to PDF.

You can hide the office windows by this task, so that the user sees nothing of you tasks.

Maybe @VRonin knows a easier way to use the .DLL in Qt.

Update:
Its available via Nuget
so it should be easy to install and try the samples directly in VS.
Then try to mix with Qt.

Update 2:
Using VBA, this short code can merge all docs from a folder.

@Andy314 I am using ActiveX but i have no idea what functions are used to do what you describe. Would you mind giving me some examples ? How do I copy and paste ? How to hide the window ?

Читайте также: