QT中文文件
QT中文翻译步骤
QT中文翻译步骤第一步在你的pro里面加入 TRANSLATIONS = myexec_zh.ts (根据对应的ts文件修改)第二步用lupdate 操作pro 将要翻译的提取到ts文件命令是 lupdate my.pro第三步用 linguist 打开刚才的ts文件,linugist是在qt的bin的目录里面, 是一个界面工具打开linguist 后用菜单栏file ->open 打开相应的ts文件如刚才myexec_zh.ts 打开后你会看到左边是相应的类右边的上半部是相应的类里面tr 里面的内容所以在程序里面 tr里面的都是e文到这里就用上了下半部是你要翻译的语言的相应的东西,就是你输入中文的地方要注意的就是那些标点符号最好还是用e文输入状态的如save as.... 就应该是另存为.... 而不是另存为。
注意后面的标点的差别,其中绿色的表示翻译好了,叹号的表示没有翻译对,交叉的表示没有翻译第四步先用 linguist 菜单保存你翻译好的ts文件,接着用linguist界面工具里面菜单file里面的release...,点击这个就会弹出对话框提示你输入 qm文件的文件名,用默认的就可以了。
按确定后你会在ts文件所在的目录看到一个qm 后缀名的个文件,这就程序翻译器要用到的文件。
第五步,在你的程序里面使用刚才得到的qm文件方法如下QTranslator translator( 0 );translator.load( "myexec_zh.qm", "." );//要跟刚才得到的qm的文件名对应app.installTranslator( &translator );切记在第五步的时候,一定要在界面的前面安装翻译器举个例子,下面的顺序是对的QTranslator translator( 0 );translator.load( "french.qm", "." );app.installTranslator( &translator );MyWidget m;app.setMainWidget( &m );m.show();下面的顺序就不对,它错在界面出来之后才才安装翻译器MyWidget m;app.setMainWidget( &m );m.show();QTranslator translator( 0 );translator.( "myexec_zh.qm", "." );//要跟刚才得到的qm的文件名对应app.installTranslator( &translator );他的错误是在界面出来后才安装翻译器,就翻译不到界面里面了,一定要在界面出来之前安装翻译器,最好就是在app后就立刻安装QTranslator translator( 0 );translator.load( "french.qm", "." );app.installTranslator( &translator );MyWidget m;m.setFont(QFont("unifont", 16));app.setMainWidget( &m );m.show();补充一下第二步的作用主要是将整个工程中所有tr的地方提取到ts文件里面,在后面打开ts的时候就会看到的,所以所谓翻译就是把tr("english")中的english 提取出来,让你翻译成相应的语言,供程序加载使用最后需要把*.qm文件copy到debug目录下,才能实现界面语言转换.qm要跟exe在一个文件夹里面,这个主要是load的时候第二个参数导致的...那个是表示exe找的qm的路径,因为是.表示当前路径,所以就有楼上上面出现的情况了,谢谢补充我的整理版:(1)在design.pro文件里面加入TRANSLATIONS = design.ts。
QT5实现语言国际化(中英文界面动态切换超详细)
QT5实现语言国际化(中英文界面动态切换超详细)QT是一款用于构建跨平台应用程序的开发框架,它支持多种编程语言,包括C++。
在QT中实现语言国际化,可以让我们的应用程序在不同语言环境下展示不同的界面文本和信息,以达到更好的用户体验。
本文将详细介绍如何在QT5中实现语言国际化,并提供一个示例。
首先,为了实现语言国际化,我们需要准备好多个翻译文件,每个文件对应一种语言。
这些文件使用Qt Linguist工具生成,可以通过以下命令创建一个翻译文件:```lupdate [项目文件] -ts [输出文件]```其中,[项目文件]是你的QT项目文件,[输出文件]是生成的翻译文件。
接下来,在QT项目中引入翻译文件。
我们可以通过以下代码将翻译文件加载到应用程序中:```cppQTranslator translator;translator.load("翻译文件路径");app.installTranslator(&translator);```在这段代码中,我们首先创建了一个QTranslator对象,然后使用load(函数加载翻译文件,最后通过installTranslator(函数将翻译文件安装到应用程序中。
假设我们的QT项目是一个简单的窗口应用程序,界面上有一个按钮,点击按钮可以切换语言。
首先,我们需要在界面上添加一个按钮,并为其添加槽函数。
槽函数的实现如下:```cppvoid MainWindow::changeLanguageQFileDialog dialog(this);dialog.setNameFilter("Translation files (*.qm)");dialog.setFileMode(QFileDialog::ExistingFile);if (dialog.exec()QString fileName = dialog.selectedFiles(.first(;QTranslator *translator = new QTranslator(this);if (translator->load(fileName))qApp->installTranslator(translator);}}```在这个槽函数中,我们首先创建了一个QFileDialog对象,用于选择翻译文件。
QString中文编码转换
QString中⽂编码转换版权声明:本⽂为博主原创⽂章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原⽂出处链接和本声明。
本⽂链接:https:///xxm524/article/details/74937308QT字符编码开发中遇到了很多坑,⼀不⼩⼼就会出现中⽂乱码,在这⾥⼩结⼀下。
QString本⾝是编码是unicode在windows下local8Bit是GBK源代码即.cpp⽂件是有编码的,不同编译器也有默认编码,如:微软VS的中的cl采⽤GBKMingw中的g++不带BOM的UTF-8Linux下的g++ 采⽤带BOM的UTF-8 这3中编码进⾏保存(所以,在代码中hard code中⽂时,要搞清楚使⽤的编译器本⾝的编码格式)QString GBK2UTF8(const QString &str){QTextCodec *utf8 = QTextCodec::codecForName("UTF-8");return utf8->toUnicode(str.toUtf8());}QString UTF82GBK(const QString &str){QTextCodec *gbk = QTextCodec::codecForName("GB18030");return gbk->toUnicode(str.toLocal8Bit());}std::string GBK2UTF8(std::string &str){QString temp = QString::fromLocal8Bit(str.c_str());std::string ret = temp.toUtf8().data();return ret;}std::string UTF82GBK(std::string &str){QString temp = QString::fromUtf8(str.c_str());std::string ret = temp.toLocal8Bit().data();return ret;}。
QT支持中文
Qt编程中的中文显示问题我刚开始学习Qt+KDevelop编程,先照Qt的指南作了个Hello World,接着试着修改QLabel("你好",...);结果出来的是乱码。
我的KDE能够正确显示中文,那么错误在哪里呢?这主要是因为文字编码的问题,qt显示用的是Unicode,而我们输入的中文一般都是gbk的,直接显示自然就是乱码了。
因此,我们需要进行编码的转换。
Qt提供了一个类专门解决这类问题,叫做QTex tCodec。
我们可以这样使用:这样转换了之后,使用string这个QString就可以正常显示了!同时,这个方法对输入的中文字符的处理一样有效。
建议你把Qt文档的关于i18n和QTextCodec类的部分好好看看,其实,那上面已经说的很明白的。
/* File: i18n.cpp */#include <iostream.h>#include <qapplication.h>#include <qtranslator.h> //信息翻译载入#include <qlabel.h>#include <qpushbutton.h>#include <qlayout.h>#include <qmultilineedit.h>#include <qmenubar.h>#include <qpopupmenu.h>class ExampleWidget : public QWidget{public:ExampleWidget( QWidget *parent = 0, const char *name = 0 );~ExampleWidget();private:};ExampleWidget::ExampleWidget( QWidget *parent, const char *name ): QWidget( parent, name ){//垂直布局QBoxLayout *topLayout = new QVBoxLayout( this, 5 );//建立菜单条QMenuBar *menubar = new QMenuBar( this );menubar->setSeparator( QMenuBar::InWindowsStyle );QPopupMenu* popup;popup = new QPopupMenu( this );popup->insertItem( tr("&Quit"), qApp, SLOT(quit()) );menubar->insertItem( tr("&File"), popup );//添加菜单条topLayout->setMenuBar( menubar );//建立水平的容器, 并添加到垂直容器中QBoxLayout *buttons = new QHBoxLayout( topLayout);int i;for ( i = 1; i <= 4; i++ ) {//建立按钮QPushButton* but = new QPushButton( this );QString s = tr("Button %1").arg(i);but->setText( s );//在水平容器上添加按钮buttons->addWidget( but, 10 );}//建立多行文本区QMultiLineEdit *bigWidget = new QMultiLineEdit( this );bigWidget->setText( tr("This widget will get all the remaining space") );bigWidget->setFrameStyle( QFrame::Panel | QFrame::Plain );//添加文本区到垂直容器中topLayout->addWidget( bigWidget);//建立标签QLabel* sb = new QLabel( this );sb->setText(tr("Let's pretend this is a status bar"));sb->setFrameStyle( QFrame::Panel | QFrame::Sunken );sb->setFixedHeight( sb->sizeHint().height() );sb->setAlignment( AlignVCenter | AlignLeft );//添加标签topLayout->addWidget( sb );//激活布局topLayout->activate();}ExampleWidget::~ExampleWidget(){ }int main( int argc, char **argv ){QApplication a( argc, argv );if(argc < 2) {cout << "Usage: ./i18n -[gb|big5]\n";exit(1);}//设置字体, 使中文程序尽量使用点阵字体.a.setFont(QFont("Times", 16, QFont::Normal));//建立Translator, 用于载入信息文件QTranslator *translator = new QTranslator(0);if(!strcmp(argv[1], "-gb")){//载入当前目录下的文件translator->load("i18n_gb.qm", ".");} else if(!strcmp(argv[1], "-big5")){//载入当前目录下的文件translator->load("i18n_big5.qm", ".");}a.installTranslator(translator);ExampleWidget f;a.setMainWidget(&f);f.show();return a.exec();}关于qt支持中文、国际化qt对国际化有很好的支持。
Qt中文翻译
Qt是一个跨平台的C++图形用户界面应用程序框架。
它提供给应用程序开发者建立艺术级的图形用户界面所需的所用功能。
Qt是完全面向对象的,很容易扩展,并且允许真正地组件编程。
它已经成为全世界范围内数千种成功的应用程序的基础。
Qt也是流行的Linux桌面环境KDE 的基础,KDE是所有主要的Linux发行版的一个标准组件。
Qt支持下述平台:MS/Windows - 95、98、NT 4.0、ME、2000、XP 和Vista,Unix/X11 - Linux、Sun Solaris、HP-UX、Compaq Tru64 UNIX、IBM AIX、SGI IRIX 和其它很多X11平台Macintosh - Mac OS X Embedded - 有帧缓冲(framebuffer)支持的Linux平台,Windows CE。
Qt是诺基亚公司的一个产品。
Qt开源版是Qt仅仅为了开发自由和开放源码软件,提供了和商业版本同样的功能。
GNU通用公共许可证下,它是免费的。
最新的版本可以在这里下载。
从2009年5月11日起,诺基亚Qt Software 宣布Qt源代码库面向公众开放,Qt 开发人员可通过为Qt 以及与Qt 相关的项目贡献代码、翻译、示例以及其他内容,协助引导和塑造Qt未来的发展。
在推出开放式Qt 代码库的同时,Qt Software 在其官方网站发布了其产品规划(Roadmap)。
其中概述了研发项目中的最新功能,展现了现阶段对Qt 未来发展方向的观点,以期鼓励社区提供反馈和贡献代码,共同引导和塑造Qt 的未来。
Qt 4.6 首次包含了对Symbian 平台的支持,并在其所支持的平台中新增了Windows 7、Apple Mac OS 10.6 (雪豹) 和即将上市的Maemo 6。
Qt 对Symbian 和Maemo 的支持首次为开发人员创造了使用同一代码库同时针对这两个平台进行开发的机会。
能够跨平台分享代码就意味着开发人员所开发的应用程序上市的速度将更快,影响的设备用户群将更广。
Qt5.9.1qmake中文手册
Qt5.9.1qmake中⽂⼿册Qt5.9.1 qmake中⽂⼿册来源:/qm843230255/article/details/77584969qmake ⼿册qmake⼯具有助于简化跨平台项⽬的开发.它⾃动⽣成Makefiles,只需要很少的信息就可以创建Makefiles。
⽆论是Qt项⽬或者是其他软件项⽬,都可以使⽤qmake。
qmake通过项⽬⽂件(.pro)⾥提供的信息⾃动⽣成Makefiles.项⽬⽂件(.pro)由开发者创建,通常项⽬⽂件(.pro)都很简单,⼤型复杂的项⽬也可以通过项⽬⽂件(.pro)创建。
qmake包含的附加功能⽀持Qt跨平台开发,qmake可以为和⾃动⽣成编译规则。
qmake可以在⽆需修改项⽬⽂件(.pro)的情况下⾃动⽣成Microsoft Visual studio项⽬。
⽬录⼤纲预览qmake⼯具提供了⼀个管理应⽤程序,库和其他组件的⾯向项⽬的系统。
可以使你控制项⽬⾥的所有源⽂件,并简明描述了构建过程中每⼀步的信息。
qmake扩展了每个项⽬中在编译和连接中运⾏必要命令的Makefile⽂件中的信息。
描述项⽬Qt项⽬通过项⽬⽂件(.pro)⽂件内容来描述这个项⽬。
qmake利⽤项⽬⽂件(.pro)中的信息⽣成Makefiles,Makefiles包含了编译项⽬所需的所有命令。
项⽬⽂件(.pro)通常包含源⽂件和头⽂件的列表,通⽤的配置信息和特定应⽤程序细节, 例如外部库链接列表,或者外部头⽂件包含⽬录列表等。
项⽬⽂件(.pro)可以包含许多不同类型的元素,包括注释,变量声明,内置函数和⼀些简单的控制结构。
⼀些最简单的项⽬中, 只需声明⽤于构建基本的配置选项的源⽂件和头⽂件。
更多关于如何创建⼀个简单的项⽬⽂件,请参考。
你可以为更复杂的项⽬创建复杂的项⽬⽂件(.pro)。
预览项⽬⽂件,参见。
关于项⽬⽂件(.pro)中使⽤变量和函数的详细信息,请看.你可以使⽤⼀个应⽤程序或者库的项⽬模板,通过指定专门的配置来调整构建过程。
Qt_Quick中文手册
我们声明类型 Rectangle 为根元素。你可以使用它在应用程序中创建一个基本块。我们这里给予它 一个 id 作为标签以便稍后引用。在这种情况里,我们命名它为“page”。同样也设置 width,height 与
color 属性。Rectangle 元素还包含许多其它的属性(例如 x 与 y);但这些我们保留它们默认的值。 Text 元素
QML 注释
在 QML 中的注释类似于 JavaScript。 单选注释以 // 开始。 多行注释以 /* 开始,以 */ 结束。
import Qt 4.7
注释是不被执行的,添加注释可对代码进行解释或者提高其可读性。 注释同样还可用于防止代码执行,这对跟踪问题是非常有用的。
Text { text: "Hello world!" //opacity: 0.5 }
Tonkv 翻译
对象是指定的类型,紧随其后是一对大括号,对象类型总是首字母为大写。在上面的示例中,有两个 对象,一个 R e ctangle[矩形]与一个 Image[图像]。在大括号之间是关于该对象特定的信息,例如 它们的属性。 属性是以 property[属性]: value[值]形式指定的。在上面的示例中,我们可以看到图像有个名为
source[来源]的属性,它的值被指定为”pics/logo.png”。该属性与它的值是由冒号来分隔。
属性是由单行来输写:
Rectangle { width: 100 height: 100 }
或单行输写多个属性:
Rectangle { width: 100; height: 100 }
当单行输写多属性/值时,必须由分号来分隔开来。
色以及列表。
Item { x: 10.5 ... state: "details" focus: true } // a 'string' property // a 'bool' property // a 'real' property
QT100资料
The QT100 charge-transfer (‘QT’) touch sensor is a self-contained digital IC capable of detecting near-proximity or touch. It will project a touch or proximity field through any dielectric like glass, plastic, stone, ceramic, and even most kinds of wood. It can also turn small metal-bearing objects into intrinsic sensors, making them responsive to proximity or touch. This capability, coupled with its ability to self-calibrate, can lead to entirely new product concepts.It is designed specifically for human interfaces, like control panels, appliances, toys, lighting controls, or anywhere a mechanical switch or button may be found.Power consumption is less than 500µA in most applications when running in Fast response mode. This typically drops to5-10µA at 2V V DD in Low Power mode, depending on the burst length. In most cases the power supply need only be minimally regulated; for example, by Zener diodes or an inexpensive three-terminal regulator. The QT100 only requires a common inexpensive X7R ceramic capacitor in order to function.The QT100’s Reduced Instruction Set Computer (RISC) core employs signal processing techniques pioneer ed by Quantum;these are specifically designed to make the device survive real-world challenges, such as ‘stuck sensor’ conditions and signal drift.The Quantum-pioneered HeartBeat™ signal is also included, allowing a microcontroller to monitor the health of the QT100continuously, if desired. By using the charge transfer principle, the IC delivers a level of performance clearly superior to older technologies in a highly cost-effective package.L QQT100C HARGE -T RANSFER QT OUCH ™ ICSNSKVSS OUTVDD SNSSYNC/MODE !2V to 5V single supply operation !10µA low power mode @ 2V !Self-calibrating on power-up !Sensitivity easily adjusted!Consensus filter for noise immunity !Autorecalibration timeout!HeartBeat™ health indicator on output !Only a few passive external parts required !RoHS compliant SOT23-6 packageQT100-ISG-40ºC to +85ºC6-pin SOT23-6T AAVAILABLE OPTIONS1 Overview1.1 IntroductionThe QT100 is a digital burst mode charge-transfer (QT) sensor designed specifically for touch controls; it includes all hardware and signal processing functions necessary to provide stable sensing under a wide variety of changing conditions. Only a single low cost, noncritical capacitor is required for operation.Figure 1.1 shows a basic circuit using the device.1.2 Basic OperationThe QT100 employs bursts of charge-transfer cycles to acquire its signal. Burst mode permits power consumption inthe microamp range, dramatically reduces RF emissions, lowers susceptibility to EMI, and yet permits excellent response time. Internally the signals are digitally processed to reject impulse noise, using a 'consensus' filter which requires four consecutive confirmations of a detection before the output is activated.The QT switches and charge measurement hardware functions are all internal to the QT100.1.3 Electrode DriveFor optimum noise immunity, the electrode should only be connected to SNSK.In all cases the rule Cs >> Cx must be observed for proper operation; a typical load capacitance (Cx) ranges from5-20pF while Cs is usually about 2-50nF.Increasing amounts of Cx destroy gain, therefore it is important to limit the amount of stray capacitance on both SNS terminals. This can be done, for example, by minimizing trace lengths and widths and keeping these traces away from power or ground traces or copper pours.The traces and any components associated with SNS and SNSK will become touch sensitive and should be treated with caution to limit the touch area to the desired location.A series resistor, Rs, should be placed in line with SNSK to the electrode to suppress ESD and EMC effects.1.4 Sensitivity1.4.1 IntroductionThe sensitivity on the QT100 is a function of things like the value of Cs, electrode size and capacitance, electrode shape and orientation, the composition and aspect of the object to be sensed, the thickness and composition of any overlaying panel material, and the degree of ground coupling of both sensor and object.1.4.2 Increasing SensitivityIn some cases it may be desirable to increase sensitivity; for example, when using the sensor with very thick panels having a low dielectric constant. Sensitivity can often be increased by using a larger electrode or reducing panel thickness. Increasing electrode size can have diminishing returns, as high values of Cx will reduce sensor gain. The value of Cs also has a dramatic effect on sensitivity, and this can be increased in value with the trade-off of slower response time and more power. Increasing the electrode's surface area will not substantially increase touch sensitivity if its diameter is already much larger in surface area than the object being detected. Panel material can also be changed to one having a higher dielectric constant, which will better help to propagate the field.Ground planes around and under the electrode and its SNS K trace will cause high Cx loading and destroy gain. The possible signal-to-noise ratio benefits of ground area are more than negated by the decreased gain from the circuit, and so ground areas around electrodes are discouraged. Metal areas near the electrode will reduce the field str ength and increase Cx loading and should be avoided, if possible. Keep ground away from the electrodes and traces.1.4.3 Decreasing SensitivityIn some cases the QT100 may be too sensitive. In this case gain can be easily lowered further by decreasing Cs.2 Operation Specifics2.1 Run Modes2.1.1 IntroductionThe QT100 has three running modes which depend on the state of SYNC, pin 6 (high or low).2.1.2 Fast ModeThe QT100 runs in Fast mode if the SYNC pin is permanently high. In this mode the QT100 runs at maximum speed at the expense of increased current consumption. Fast mode is useful when speed of response is the prime design requirement. The delay between bursts in Fast mode is approximately 1ms, as shown in Figure 2.2.2.1.3 Low Power ModeThe QT100 runs in Low Power (LP) mode if the SYNC line is held low. In this mode it sleeps for approximately 70ms at the end of each burst, saving power but slowing response. On detecting a possible key touch, it temporarily switches to Fast mode until either the key touch is confirmed or found to be spurious (via the detect integration process). It then returns to LP mode after the key touch is resolved as shown in Figure 2.1.Figure 1.1 Basic Circuit Configuration2.1.4 SYNC ModeIt is possible to synchronize the device to an external clock source by placing an appropriate waveform on the SYNC pin.SYNC mode can synchronize multiple QT100 devices to each other to prevent cross-interference, or it can be used to enhance noise immunity from low frequency sources such as 50Hz or 60Hz mains signals.The SYNC pin is sampled at the end of each burst. If the device is in Fast mode and the SYNC pin issampled high, then the device continues to operate in Fast mode (Figure 2.2). If SYNC is sampled low, then the device goes to sleep. From then on, it will operate in SYNC mode (Figure 2.1). Therefore, to guarantee entry into SYNC mode the low period of the SYNC signal should be longer than the burst length (Figure 2.3).However, once SYNC mode has been entered, if the SYNC signal consists of a series of short pulses(>10µs) then a burst will only occur on the leading edge of each pulse (Figure 2.4) instead of on each change of SYNC signal, as normal (Figure 2.3).In SYNC mode, the device will sleep after each measurement burst (just as in LP mode) but will be awakened by a change in the SYNC signal in either direction, resulting in a new measurement burst. IfSYNC remains unchanged for a period longer than the LP mode sleep period (about 70ms), the device will resume operation in either Fast or LP mode depending on the level of the SYNC pin (Figure 2.3).There is no DI in SYNC mode (each touch is adetection) but the Max On-duration will depend on the time between SYNC pulses; see Sections 2.3 and 2.4.Recalibration timeout is a fixed number ofmeasurements so will vary with the SYNC period.2.2 ThresholdThe internal signal threshold level is fixed at 10 counts of change with respect to the internal reference level,which in turn adjusts itself slowly in accordance with the drift compensation mechanism.The QT100 employs a hysteresis dropout of two counts of the delta between the reference and threshold levels.2.3 Max On-durationIf an object or material obstructs the sense pad thesignal may rise enough to create a detection, preventing further operation. To prevent this, the sensor includes a timer which monitors detections. If a detection exceeds the timer setting the sensor perform s a full recalibration.This is known as the Max On-duration feature and is set to ~60s. This will vary slightly with Cs and if SYNC mode is used. As the internal timebase for Max On-duration is determined by the burst rate, the use of SYNC can cause dramatic changes in this parameter depending on the SYNC pulse spacing.2.4 Detect IntegratorIt is desirable to suppress detections generated by electrical noise or from quick brushes with an object. To accomplish this, the QT100 incorporates a ‘detect integration’ (DI)counter that increments with each detection until a limit is reached, after which the output is activated. If no detection is sensed prior to the final count, the counter is resetimmediately to zero. In the QT100, the required count is four.In LP mode the device will switch to Fast mode temporarily in order to resolve the detection more quickly; after a touch is either confirmed or denied the device will revert back to normal LP mode operation automatically.The DI can also be viewed as a 'consensus' filter, that requires four successive detections to create an output.Figure 2.1 Low Power Mode (SYNC held low)2.5 Forced Sensor RecalibrationThe QT100 has no recalibration pin; a forced recalibration is accomplished when the device is powered up or after the recalibration timeout.However, supply drain is low so it is a simplematter to treat the entire IC as a controllable load;driving the QT100's V DD pin directly from another logic gate or a microcontroller port will serve as both power and 'forced recal'. The source resistance of most CMOS gates andmicrocontrollers are low enough to provide direct power without problem.2.6 Drift CompensationSignal drift can occur because of changes in Cx and Cs over time. It is crucial that drift becompensated for, otherwise false detections, nondetections,and sensitivity shifts will follow.Drift compensation (Figure 2.5) is performed by making the reference level track the raw signal at a slow rate, but only while there is no detection in effect. The rate of adjustment must be performed slowly, otherwise legitimate detections could be ignored. The QT100 drift compensates using aslew-rate limited change to the reference level; the threshold and hysteresis values are slaved to this reference.Once an object is sensed, the drift compensation mechanism ceases since the signal is legitimately high , and therefore should not cause the reference level to change.The QT100's drift compensation is 'asymmetric'; thereference level drift-compensates in one direction faster than it does in the other. Specifically, it compensate s faster for decreasing signals than for increasing signals. Increasing signals should not be compensated for quickly, since an approaching finger could be compensated for partially or entirely before even approaching the sense electrode.However, an obstruction over the sense pad, for which the sensor has already made full allowance, could suddenly be removed leaving the sensor with an artificially elevatedreference level and thus become insensitive to touch. In this latter case, the sensor will compensate for the object's removal very quickly, usually in only a few seconds.With large values of Cs and small values of Cx, driftcompensation will appear to operate more slowly than with the converse. Note that the positive and negative drift compensation rates are different.2.7 Response TimeThe QT100's response time is highly dependent on run mode and burst length, which in turn is dependent on Cs and Cx.With increasing Cs, response time slows, while increasing levels of Cs reduce response time. The response time will also be a lot slower in LP or SYNC mode due to a longer time between burst measurements.2.8 Spread SpectrumThe QT100 modulates its internal oscillator by ±7.5% during the measurement burst. This spreads the ge nerated noise over a wider band reducing emission levels. This also reduces susceptibility since there is no longer a single fundamental burst frequency.2.9 Output Features2.9.1 OutputThe output of the QT100 is active-high upon detection. The output will remain active-high for the duration of thedetection, or until the Max On-duration expires, whichever occurs first. If a Max On-duration timeout occurs first, the sensor performs a full recalibration and the output becomes inactive (low) until the next detection.Figure 2.5 Drift CompensationFigure 2.7Using a micro to obtain HeartBeat pulses in either output stateFigure 2.6Getting HeartBeat pulses with a pull-up resistor2.9.2 HeartBeat™ OutputThe QT100 output has a HeartBeat™ ‘health’ indicator superimposed on it in both LP and SYNC modes. This operates by taking the output pin into a three-state mode for 15µs once before every QT burst. This output state can be used to determine that the sensor is operating properly, or, it can be ignored using one of several simple methods.The HeartBeat indicator can be sampled by using a pull-up resistor on the OUT pin, and feeding the resultingpositive-going pulse into a counter, flip flop, one-shot, or other circuit. The pulses will only be visible when the chip is not detecting a touch.If the sensor is wired to a microcontroller as shown inFigure 2.7, the microcontroller can reconfigure the load resistor to either V SS or V DD depending on the output state of the QT100, so that the pulses are evident in either state. Electromechanical devices like relays will usually ignore th e short Heartbeat pulse. The pulse also has too low a duty cycle to visibly affect LEDs. It can be filtered completely if desired, by adding an RC filter to the output, or if interfacing directly and only to a high-impedance CMOS input, by doing nothing or at most adding a small noncritical capacitor from OUT to V SS.2.9.3 Output DriveThe OUT pin is active high and can sink or source up to 2mA. When a large value of Cs (>20nF) is used the OUT current should be limited to <1mA to prevent gain-shifting side effects, which happen when the load current creates vol tage drops on the die and bonding wires; these small shifts can materially influence the signal level to cause detection instability.3 Circuit Guidelines3.1 Application NoteRefer to Application Note AN-KD02, downloadable from the Quantum website for more information on construction and design methods. Go to , click the Support tab and then Application Notes.3.2 Sample CapacitorCharge sampler capacitor Cs should be a stable type, such as X7R ceramic or PPS film. The normal Cs range is from2nF to 50nF depending on the sensitivity required; larger values of Cs demand higher stability to ensure reliab le sensing. For more consistent sensing from unit to unit, 5% tolerance capacitors are recommended. X7R ceramic types can be obtained in 5% tolerance at little or no extra cost.Values of Cs above 100nF will only be required for large values of Cx. Sensing may become unstable if Cx is small and Cs is large; for example, in attempting to implement proximity fields.3.3 Power Supply, PCB LayoutThe power supply can range between 2.0V and 5.0V. At 3V current drain averages less than500µA in Fast mode.If the power supply is shared with another electronic system, care should be taken to assure that the supply is free of digital spikes, sags, and surges which can adversely affect the QT100. The QT100 will track slow changes in V DD, but it can be badly affected by rapid voltage fluctuations. It is highly recommended that a separate voltage regulator be used just for the QT100 to isolate it from power supply shifts caused by other components.If desired, the supply can be regulated using a Low Dropout (LDO) regulator, although such regulators often have poor transient line and load stability. See Application NoteAN-KD02 (see Section 3.1) for further information on power supply considerations.Parts placement: The chip should be placed to minimize the SNSK trace length to reduce low frequency pickup, and to reduce stray Cx which degrades gain. The Cs and Rs resistors (see Figure 1.1) should be placed as close to the body of the chip as possible so that the trace between Rs and the SNSK pin is very short, thereby reducing the antenna-like ability of this trace to pick up high frequency signals and feed them directly into the chip. A ground plane can be used under the chip and the associated discretes, but the trace from the Rs resistor and the electrode should not run near ground to reduce loading.For best EMC performance the circuit should be made entirely with SMT components.Electrode trace routing: Keep the electrode trace (and the electrode itself) away from other signal, power, and ground traces including over or next to ground planes. Adjacent switching signals can induce noise onto the sensing signal; any adjacent trace or ground plane next to, or under, the electrode trace will cause an increase in Cx load and desensitize the device.Important Note: for proper operation a 100nF (0.1µF) ceramic bypass capacitor must be used directly between V DD and V SS, to prevent latch-up; the bypass capacitor should be placed very close to the device’s power pins.4 Specifications4.1 Absolute Maximum SpecificationsOperating temp........................................................................................................-40ºC to +85ºC Storage temp........................................................................................................-55O C to +125O C V DD ...................................................................................................................-0.5 to +5.25V Max continuous pin current, any control or drive pin..............................................................................±20mA Short circuit duration to V SS , any pin.............................................................................................infinite Short circuit duration to V DD , any pin............................................................................................infinite Voltage forced onto any pin...................................................................................-0.6V to (V DD + 0.6) Volts4.2 Recommended Operating ConditionsV DD .....................................................................................................................+2.0 to 5.0V Short-term supply ripple+noise..................................................................................................±5mV Long-term supply stability....................................................................................................±100mV Cs value.................................................................................................................2nF to 50nF Cx value...................................................................................................................5 to 20pF4.3 AC SpecificationsV DD = 3.0V, Cs = 10nF, Cx = 5pF, Ta = recommended range, unless otherwise noted µs15Heartbeat pulse widthT HBms 100Response time T R Cs and Cx dependentms Burst length T BL V DD =5V. Increases with reducing V DD ms 70Time between end of burst and start of the next (LP mode)T G 2V DD =5Vms 1Time between end of burst and start of the next (Fast mode)T G 1±7.5% spread spectrum variation µs 2Transfer durationT PT ±7.5% spread spectrum variation µs 2Charge duration T PC Cs, Cx dependentms 250Recalibration time T RC NotesUnits MaxTyp MinDescriptionParameter4.4 Signal ProcessingWill vary in SYNC modesecs30Post-detection recalibration timer durationms/level 1,000Negative drift compensation ratems/level 2,000Positive drift compensation rate samples 4Consensus filter length counts 2Hysteresiscounts 10Threshold differential NotesUnits MaxTyp MinDescription4.5 DC SpecificationsV DD = 3.0V, Cs = 10nF, Cx = 5pF, Ta = recommended range, unless otherwise noted bits149Acquisition resolutionA RpF 1000Load capacitance range C X µA ±1Input leakage current I IL OUT, 1mA sourceV V DD -0.7High output voltage V OH OUT, 4mA sink V 0.6Low output voltage V OL V 2.2High input logic level V HL V 0.8Low input logic level V IL Required for proper start-upV/s 100Supply turn-on slope V DDS Depending on supply and run mode µA 6005Supply current I DD V 5.252Supply voltage V DD NotesUnitsMaxTyp MinDescriptionParameter4.6 Mechanical Dimensions10º0º10º0ºØ 0.0080.0040.20.09e0.0220.0140.550.35E 0.020.0140.50.35L 0.038 BSC--0.95 BSC --D 0.00600.150.0h 0.0510.0351.30.9H 0.0690.0591.751.5Aa 0.1180.1023.02.6W 0.1220.1103.102.8M NotesMaxMinNotesMax MinInches Millimeters SymbolPackage type: SOT23-64.7 Marking02NN (where NN is variable)QT100-ISG-40C to +85CMarkingSOT23-6 Part NumberT ANOTES:l Q Copyright © 2006 QRG Ltd. All rights reservedPatented and patents pendingCorporate Headquarters1 Mitchell PointEnsign Way, Hamble SO31 4RFGreat BritainTel: +44 (0)23 8056 5600 Fax: +44 (0)23 8045 3939North America651 Holiday Drive Bldg. 5 / 300Pittsburgh, PA 15220 USATel: 412-391-7367 Fax: 412-291-1015This device is covered under one or more United States and corresponding international patents. QRG patent numbers can be found online at . Numerous further patents are pending, which may apply to this device or the applications thereof.The specifications set out in this document are subject to change without notice. All products sold and services supplied by QRG are subject to our Terms and Conditions of sale and supply of services which are available online at and are supplied with every order acknowledgement. QRG trademarks can be found online at . QRG products are not suitable for medical (including lifesaving equipment), safety or mission critical applications or other similar purposes. Except as expressly set out in QRG's Terms and Conditions, no licenses to patents or other intellectual property of QRG (express or implied) are granted by QRG in connection with the sale of QRG products or provision of QRG services. QRG will not be liable for customer product design and customers are entirely responsible for their products and applications which incorporate QRG's products.。
利用QT生成Word文档
28. void SetTableCellString(QAxObject *table, int row,int column,QString tex
t);
29.
30. private:
31.
32. QAxObject *m_pWord;
//指向整个 Word 应用程序
33.
QAxObject *m_pWorkDocuments; //指向文档集,Word 有很多文档
19.
20. bool replaceText(QString sLabel,QString sText);
21. bool replacePic(QString sLabel,QString sFile);
22.
//插入一个几行几列表格
23. QAxObject *insertTable(QString sLabel,int row,int column);
24.
//插入一个几行几列表格 并设置表头
25. QAxObject *insertTable(QString sLabel,int row,int column,QStringList hea
dList);
26.
//设置列宽
27. void setColumnWidth(QAxObject *table,int column, int width);
2、编写 word 操作接口类,主要包括:打开、关闭、保存、插入文本、插入图片、插入表格、 相关格式调整函数
3、编写生成报告界面类,调用接口函数生成 word 文档。
二、接口函数
WordEngine.h 文件
Байду номын сангаас
[cpp] view plain copy
qt中文翻译文档
中文汉化Linux 下开发中文应用程序不像在windows 下那样方便,但我们同样可以实现,我们需要QTranslator 类对语言进行翻译. QTranslator 是一个翻译器类,我们通过定义其对象进行翻译 具体实例如下 m_translator = new QTranslator(0);m_translator->load( "zh.qm", "." );qApp->installTranslator( m_translator ); “zh.qm ”是一个翻译文件,我们将需要翻译的字符用tr()包裹,这个必须在后续操作之前完成tr("menu bar")生成“zh.qm ”文件的方法:1,在工程文件中(*.pro)加上一条语句TRANSLATIONS = zh.ts其中” zh.ts ”是要生成的ts 文件,这个文件里面是所有要翻译的字符的集合 2,在终端输入命令lupdate specana.pro 这条命令可以生成上面所述的zh.ts 文件, 3,输入命令打开linguist 工具 linguist这个工具是翻译工具,原先的zh.ts 文件中只保存了所有需要翻译的文字,但还未翻译,同过运行linguist 工具,可以手动将需要翻译的文字和翻译文字对应 k e v i n打开我们生成 *.ts 文件在Translation 栏目中手动输入要翻译成的文字.(完成一个后用CTRL+ENTER 跳转到下一个), 此时可能会出现红色的感叹号警告,这个时候就注意一下是否翻译后的标点符号和原文的一致.最后保存关闭4,最后一个过程是生成我们要用的”zh.qm ”文件,在命令行输入lrelease zh.ts此命令可以生成zh.qm 文件,这个文件用记事本打开为乱码的, k e v in将zh.qm文件放在想对应目录下就可以了,我们在程序里写的目录是”.”,所以在PC机上的对应目录是程序目录,而在开发板上对应的目录是在”/”目录最后要注意的是,在每次添加新的需要翻译的文字时,上述步骤都要重新做….这也是麻烦的地方,并且想要动态生成中文的文字也比较麻烦.nivek。
中文字符串转换为QString
最直接的方法是把整个应用程序的编码设置为GBK编码,然后在字符串这前加tr:
CODE:
qApp->setDefaultCodec( QTextCodec::codecForName("GBK") );
...
QLabel *label = new QLabel(tr("你好,世界!"));
QFile
QFile类是一个操作文件的输入/输出设备。
QFile是用来读写二进制文件和文本文件的输入/输出设备。QFile可以自己单独被使用,但是如果和QDataStream或QTextStream一起使用将更加方便。
文件名通常可以通过构造函数来传递,但也可以使用setName()来设置。你可以通过exists()来检查一个文件是否存在并且可以通过remove()来移去一个文件。
法二:
QTextCodec::setCodecForTr(QTextCodec::codecForLocale());
-----------------------------------------------------------------------------------------
网上搜了下QT4用的默认字体,没有查到,又看了QT4的源代码,代码太多,也没有找到。
不过setFont函数引起了我的注意,在网上看到过这种方法。”
参考上面的内容,修改代码:
...
QTextCodec::setCodecForTr(QTextCodec::codecForName("gb18030"));
QT中文 乱码解决
QString 与中文问题2010-07-11 17:04(更新:本文的姊妹篇Qt中translate、tr关系与中文问题 )首先呢,声明一下,QString 是不存在中文支持问题的,很多人遇到问题,并不是本身 QString 的问题,而是没有将自己希望的字符串正确赋给QString。
很简单的问题,"我是中文"这样写的时候,它是传统的 char 类型的窄字符串,我们需要的只不过是通过某种方式告诉QString 这四个汉字采用的那种编码。
而问题一般都出在很多用户对自己当前的编码没太多概念,于是一个简单的 Qt 程序下面这个小程序,估计大家会感到比较亲切。
似乎有相当多的中文用户尝试写过这样的代码:#include <QtGui/QApplication>#include <QtGui/QLabel>int main(int argc, char **argv){QApplication app(argc, argv);QString a= "我是汉字";QLabel label(a);label.show();return app.exec();}编码,保存,编译,运行,一切都很顺利,可是结果呢:出乎意料,界面上中文没显示出来,出现了不认识字符。
于是开始用搜索引擎搜索,开始上论坛发帖或抱怨最后被告知,下面的语句之一可以解决问题:两条指令挨个一试,确实可以解决(多数用户是第一条,其他用户是第二条)。
那么,为什么会这样呢?两种乱码什么时候出现对这个问题,我想大家可能都有话说。
在继续之前,我们先列个表,看看两种乱码分别在那种情况下出现:我们只列举大家最常用的3个编译器(微软VS的中的cl,Mingw中的g++,Linux 下的g++),源代码分别采用GBK和不带BOM的UTF-8 以及带BOM的UTF-8 这3中编码进行保存。
采用3种不同编码保存的源代码文件,分别用3种不同的编译器编译,形成9种组合,除掉一种不能工作的情况,两种乱码出现的情况各占一半。
qt中制作添加.ts翻译文件
qt中制作添加.ts翻译⽂件QT 中可以⽤其⾃⾝的⼯具对界⾯语⾔进⾏翻译,以实现⽀持语⾔的效果,这对于开发⽤户跨越语⾔区域的⼯具来说是⼀个特别实⽤的功能。
下⾯介绍怎么制作和使⽤qt的翻译⽂件:⼀、⽣成.ts翻译⽂件(.ts是可读的翻译⽂件,使⽤简单的XML格式)1. 启动qt的命令⾏⼯具:开始 -> 程序-> qt4.7.0 -> qt4.7.0 commond prompt ;2. 在命令⾏窗⼝中,进⼊到⼯程⽬录;3. 利⽤编辑⼯具打开.pro⽂件,在末尾添加 TRANSLATIONS += yourproject_zh.ts 等号右边的名字可以⾃⼰取,⽐如中⽂的就⽤后缀_zh, 英⽂的就⽤ _en ,便于识别 4. 然后回到qt命令⾏窗⼝,执⾏ lupdate –verbose yourproject.pro //⽣成相应的.ts ⽂件⼆、编辑 .ts⽂件 1)接上,在命令⾏窗⼝中执⾏ linguist //启动Linguist语⾔翻译⼯具,可以翻译相应可见字符串 (启动:命令⾏或者开始菜单均可) 2)打开:⼯具界⾯中的File--->Open,可以打开所需的 .ts ⽂件 3)翻译:界⾯中部的翻译栏,两⾏:第⼀⾏:Source Text 第⼆⾏:… Translation, 在地⼆⾏进⾏相应的翻译即可,翻译完⼀条之后点击“确定下⼀个”按钮。
保存即可。
三、⽣成.qm⽂件(.qm是经过.ts转换⽽成的⼆进制机器语⾔) lrelease –verbose spreadsheet.pro //将翻译好的⽂件⽣成.qm⽂件四、修改或新加⼊界⾯部件时只需从 lupdate -verbose 这⼀步开始执⾏,即可。
然后把⽣成的.qm⽂件放到正确的⽬录中,即可实现翻译的效果。
如果是安装了插件的visual studio ,也可以右击解决⽅案,实现 lupdate 和 lrelease 命令同样的功能。
Qt4中文教程教本[完整版]
Qt 4.2 白皮书
奇趣科技
1
Qt 4.2 白皮书 © 2006 Trolltech ASA 版权所有
摘 要
此白皮书介绍了 Qt C++ 框架。Qt 采用“一写永逸”的方法支持开发跨平台的 GUI 应用程序。使用单一源码树和简单的重编译方式,可以为 Windows 98 至 Windows XP、 Mac OS X、 Linux、 Solaris、 HP-UX 以及其他使用 X11 的 Unix 版本编写各种程序。 此 外,还可以编译在嵌入式 Linux 平台中运行的 Qt 应用程序。Qt 引入了一种名为“信号和 槽”的独特对象间通信机制。 Qt 还为 2D 和 3D 图形、 国际化、 SQL、 XML、 单元测试提供了 卓越的跨平台支持,并为特定应用程序提供了针对具体平台的扩展。您可以使用 Qt Designer(Qt 设计者)(一种支持 IDE 集成的灵活用户界面构建器)构建器来可视书 © 2006 Trolltech ASA 版权所有
目录
1. 简介................................................................................................................................. 6 1.1. 内容概要...................................................................................................................... 6 2. 窗体..............................
qtcreator使用ibus输入中文的方法
在Qt Creator中使用iBus输入中文的方法如下:
1.确保你已经安装了iBus输入法框架。
如果还没有安装,可以通过终端输入
sudo apt-get install ibus-qt4进行安装。
2.在Qt Creator中打开设置(File > Preferences),选择“环境”选项
卡。
3.在“环境”选项卡中,找到“文本编辑器”部分,勾选“使用系统默认的文
本编辑器”选项。
4.确认设置并退出设置窗口。
5.在终端中输入export GTK_IM_MODULE=ibus,然后按Enter键。
6.接着输入export XMODIFIERS=@im=ibus,然后按Enter键。
7.最后输入export QT_IM_MODULE=ibus,然后按Enter键。
8.重启Qt Creator。
现在,你应该能够在Qt Creator中使用iBus输入法输
入中文了。
请注意,这些步骤可能会因操作系统和Qt Creator版本的不同而有所差异。
如果遇到问题,可以查看Qt Creator的文档或搜索相关教程以获取更多帮助。
QT之QJson传输和中文乱码解决方案
QT之QJson传输和中⽂乱码解决⽅案版权声明:本⽂为博主原创⽂章,转载请注明出处,谢谢⼤家的分享。
https:///x348722662/article/details/53444294 QT之QJson传输和中⽂乱码解决⽅案本⽂对遇到QJson的解析和传输遇到的些问题作出⼀些解决的办法qt中传输json数据qt接收json数据中包含中⽂转换qt传输json数据Qt5中JSON的⽣成与解析QJsonDocumentQJsonDocument既可以从⼀个基于⽂本表⽰的UTF-8编码,⼜可以从Qt⾃⼰的⼆进制格式读取和写⼊这个⽂件。
JSON⽂档可以从它的基于⽂本的表⽰使⽤QJsonDocument::fromJson()转换为QJsonDocument,⽤.toJSON()将其转换回⽂字。
解析器⾮常快速和⾼效,将JSON转换为⼆进制表⽰。
QJsonObjectQJsonObject类⽤于封装JSON对象。
JSON对象是键值对,其中键是唯⼀的字符串,其值由QJsonValue代表。
⼀个QJsonObject可以从QVariantMap转换/被转换。
QJsonArrayQJsonArray类⽤于封装JSON数组。
⼀个JSON数组列表值。
该列表可以通过从阵列插⼊和移除QJsonValue的操纵。
⼀个QJsonArray可以从QVariantList转换为/被转换。
⽂档中包含的数组或对象可以使⽤array()或object()进⾏检索,然后读取或操纵。
⽰例QJsonObject(1)⽣成JsonQJsonObject json;json.insert("name", QString("Qt"));json.insert("version", 5);json.insert("windows", true);QJsonDocument document;document.setObject(json);QByteArray byte_array = document.toJson(QJsonDocument::Compact);QString json_str(byte_array);结果:json_str:{"name": "Qt","version": 5,"windows": true}(2)解析JsonQJsonParseError json_error;QJsonDocument parse_doucment = QJsonDocument::fromJson(byte_array, &json_error);if(json_error.error == QJsonParseError::NoError){if(parse_doucment.isObject()){QJsonObject obj = parse_doucment.object();if(obj.contains("name")){QJsonValue name_value = obj.take("name");if(name_value.isString()){QString name = name_value.toString();}}if(obj.contains("version")){QJsonValue version_value = obj.take("version");if(version_value.isDouble()){int version = version_value.toVariant().toInt();}}if(obj.contains("windows")){QJsonValue version_value = obj.take("windows");if(version_value.isBool()){bool flag = version_value.toBool();}}}}qt接收json数据中包含中⽂转换因为在实际项⽬中,遇到json中含有汉字,在转换显⽰的时候出现乱码,如果我们要⽤QString的时候,所以我们在接收完之后进⾏⼀个转换:void Receiver::dataread(){while(tcp_Msg->bytesAvailable()>0){QByteArray datagram;datagram.resize(tcp_Msg->bytesAvailable());tcp_Msg->read(datagram.data(),datagram.size());//在这⾥我们进⾏⼀个转换,之后就可以⽤QJson分析把我们收到的json数据QString str = QString::fromLocal8Bit(datagram.data());analysis(str);}}}之后我们进⾏解析含有中⽂的json数据,关键代码如下void ReceiverWB::analysis(QString msg){QJsonParseError json_error;QJsonDocument parse_doucment = QJsonDocument::fromJson(msg.toStdString().data(), &json_error);if(json_error.error == QJsonParseError::NoError){if(parse_doucment.isObject()){QJsonObject obj = parse_doucment.object();if(obj.contains("name")){QJsonValue name_value = obj.take("name");if(name_value.isString()){//在这⾥我们把汉字的名称做了转换,保存到tmpCamre->name⾥{"name":"张三"}QString str = QString::fromLocal8Bit(name_value.toString().toLocal8Bit().data());strcpy(tmpCamra->Name,str.toStdString().data());}}}}}⼩结:以上便是在实际应⽤中遇到的乱码的问题,希望对有遇到此问题的朋友,有所帮助。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
oct设置QTextStream来读/写八进制数字
dec设置QTextStream来读/写十进制数字
hex设置QTextStream来读/写十六进制数字
endl强制换行
flush强制QIODevice刷新任何被缓存的数据
ws作为任何可用的控制符(在输入的时候)
reset重新设置QTextStream为它的缺省模式(请见reset())
for ( QStringList::Iterator it = lines.begin(); it != lines.end(); ++it )
stream << *it << "\n";
fi
line = codec->fromUnicode(floStream.readLine());
qWarning(line);
}
file.close();
}
return 0;
}
代码中的主要改动就是黄底的部分
意思就是创立一个中文GBK编码样式,然后按照这种方式来把读入的文件流进行重新编码,这样中文就可以顺利输出了,不信你可以试一试
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
补上这两句就可以了显示中文了
#include <qtextcodec.h>
QTextCodec::setCodecForTr(QTextCodec::codecForName("GB2312")) ;
也可以参考QDataStream、输入/输出和网络和文本相关类.
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include <qfile.h>
#include <qtextstream.h>
#include <qtextcodec.h>
int main()
{
QFile file("test.txt");
if (file.open(IO_ReadOnly|IO_Raw))
{
QTextStream floStream(&file);
QString line;
QTextCodec *codec=QTextCodec::codecForName("GBK");
floStream.setCodec(codec);
while ( floStream.atEnd()==0 )
文件可以用open()来打开、用close()来关闭、用flush()来刷新。数据通常可以使用QDataStream或者QTextStream进行读写,但你也可以使用readBlock()和readLine()来读,使用writeBlock()来写。QFile也支持getch()、 ungetch()和putch()。
}
file.close();
}
写文本也很容易(假设我们有一个行的字符串列表要写):
QFile file( "file.txt" );
if ( file.open( IO_WriteOnly ) ) {
QTextStream stream( &file );
字符串列表可以使用QStringList类来处理。你可以使用QStringList::split()来把一个字符串分割为一个字符串列表,并且可以使用QStringList::join()把一个字符串列表连接成一个使用随意间隔符的字符串。你也可以使用QStringList::grep()从一个字符串列表中获得包含特定子字符串或者包含匹配特定的regex的字符串列表。
while ( !stream.eof() ) {
line = stream.readLine(); // 不包括“\n”的一行文本
printf( "%3d: %s\n", n++, tin1() );
lines += line;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
代码部分
#include <qstring.h>
QFile
QFile类是一个操作文件的输入/输出设备。
QFile是用来读写二进制文件和文本文件的输入/输出设备。QFile可以自己单独被使用,但是如果和QDataStream或QTextStream一起使用将更加方便。
文件名通常可以通过构造函数来传递,但也可以使用setName()来设置。你可以通过exists()来检查一个文件是否存在并且可以通过remove()来移去一个文件。
QIODevice在构造函数中被设置,或者之后在setDevice()中使用。如果输入到达了atEnd(),返回真。数据可以使用operator>>()重载操作符读到适当类型的变量中,或者使用read()把它作为整个部分读到一个单一的字符串中,或者使用readLine()把一次读一行。使用skipWhiteSpace()可以忽略控制符。你可以使用flags()或setf()来设置流的标记。这个流也支持width()、precision()和 fill(),使用reset()可以重新恢复默认设置。
QTextCodec
QTextCodec 类提供文本编码之间的转换。
QT使用Unicode来存储,绘制以及操作字符串。在很多情况下,你可能想要使用不同的编码方式来处理数据。例如大部分的日语文件都被存储在Shift-JIS或者 ISO2022的文件中,而俄罗斯的用户常常使用KOI8-R或者CP1251编码方式。QT提供了一个QTextCodec 类集合来从Unicode格式转化到相应的格式。
所有的QString的方法都使用const char *参数,const char *被解释为经典的C风格的以零结尾的ASCII字符串。所以const char *参数为0是合法的。如果const char *不是以零结尾的,结果是不确定的。把经典的C字符串复制到QString的函数将不会复制结尾的0字符。QString的QChar数组(可以通过unicode()返回)通常不以零结尾。如果你需要把QString传递到一个需要C的以零结尾的字符串,请使用latin1()。
#include <qfile.h>
#include <qtextstream.h>
#include <qtextcodec.h>
QString
QString类提供了一个Unicode文本和经典的C以零结尾的字符数组的抽象。
QString使用隐含共享,这使它非常有效率并且很容易使用。
QFile file( "file.txt" );
if ( file.open( IO_ReadOnly ) ) {
QTextStream stream( &file );
QString line;
int n = 1;
注意如果你发现你正在混合使用QCString、QString和QByteArray,这将会导致很多不必要的复制并且也许会预示着你正在处理的真实自然数据是不确定的。如果数据是以零结尾的八位数据,请使用QCString;如果它是没有结尾的(也就是包含0)八位数据,请使用QByteArray;如果它是文本,请使用QString。
没有分配任何东西的QString是零,也就是长度和数据指针都为0。引用空字符串(“”,一个单一的'\0'字符)的QString是空。零和空这两个QString在方法中都是合法的。把(const char *) 0赋值给QString给定了一个零QString。为了方便,QString::null是一个零QString。当排序的时候,空字符串在最前面,然后是非空字符串,然后才是零字符串。我们建议使用if ( !str.isNull() ),而不是if ( !str )来检测非零字符串,关于解释说明也可以参考operator!()。
qSetW(int)设置字段宽度作为指定参数
qSetFill(int)设置填充字符作为指定参数
qSetPrecision(int)设置精确度作为指定参数
警告:默认情况下,QTextStream在读取流的时候,会自动地检测流中的数字是十进制、八进制、十六进制或者二进制格式。具体情况是,一个以“0”为开头的数字是八进制的,比如顺序为“0100”将会被解释为64。
QTextStream类读写文本,它不适合处理二进制数据(而QDataStream是适合的)。
默认情况下,输出的是使用本地8位编码后的Unicode文本(比如,QString)。这些可以使用setEncoding()方法进行改变。对于输入,QTextStream会自动检测标准Unicode“字节顺序标记的”文本文件,否则会使用本地8位编码。
QT中文文件
虽然C++标准中有了文件读取的相关类,也很好用,但是在涉及到QT编程的时候却用起来不方便了,因为QT本身很多组件都是关联的自身的QString类型的字符串,所以再用C++本身String类型的时候就不是那么方便了,需要进行转化,这样给程序带来了复杂度,同时也带来了转化的开销,所以如果用QT开发,可以就用它本身所带的这些类型进行处理,形成一个系统,便于数据在程序之中的交互和共用。