草庐IT

Qt之语言家的简单使用(一)(Qt翻译UI,Qt Linguist的使用,含源码+注释)

lw向北. 2023-09-09 原文

文章目录

一、翻译程序示例图

下图包含两个窗口,先弹出一个对话框,然后点击按钮切换语言。

二、流程须知(个人理解)

  1. 想要使用翻译类生成文件,需要在pro文件中指定生成目录,如本文pro文件中的TRANSLATIONS = Language/linguist_cn.ts Language/linguist_en.ts,其中Language/为ts、qm文件包含目录,该文件夹存在于pro文件同级目录中(不设置包含目录则两种类型文件生成在pro同级目录中)。
  2. 代码中包含文本时需添加使用tr函数包含文本,使其在生成ts文件时能识别到;提示:tr函数使用方法建议单独查看
  3. 当编辑完成后后,通过下图方式生成ts文件(存在则覆盖);
  4. 使用Qt Linguist打开ts文件,如下图方式编辑翻译,然后保存;
  5. 然后如下图方式生成qm文件操作(存在则覆盖);
    (生成当前ts文件的qm文件)


    (生成当前项目中所有ts文件的qm文件)
    最后如代码中使用即可。

三、关于对话框中QDialogButtonBox翻译的操作

在ts文件中需要手动添加如下代码,这就是为什么我Qt Linguist打开ts文件会多一项“QPlatformTheme”的原因,具体原因请查看Qt QDialogButtonBox 英文翻译问题

 <context>
    <name>QPlatformTheme</name>
    <message>
        <location filename="../CTipDialog.ui"/>
        <source>OK</source>
        <translation>确定</translation>
    </message>
    <message>
        <source>Cancel</source>
        <translation>取消</translation>
    </message>
</context>

四、源码

CLinguistTest.h

#ifndef CLINGUISTTEST_H
#define CLINGUISTTEST_H

#include "CTipDialog.h"
#include <QMainWindow>
#include <QTranslator>

namespace Ui {
class CLinguistTest;
}

class CLinguistTest : public QMainWindow
{
    Q_OBJECT

public:
    explicit CLinguistTest(QWidget *parent = nullptr);
    ~CLinguistTest();

private slots:
    // 语言切换槽函数
    void on_switchLanguageBtn_clicked();

private:
    Ui::CLinguistTest   *ui;

    bool                m_languageFlag; // 语言标记值(true为中文,false为英语)

    CTipDialog          *m_dialog;  // 对话框指针

    QTranslator         *m_translator;  // 翻译类对象指针
};

#endif // CLINGUISTTEST_H

CLinguistTest.cpp

#include "CLinguistTest.h"
#include "ui_CLinguistTest.h"
#include "CTipDialog.h"
#include <QApplication>
#include <QPushButton>

CLinguistTest::CLinguistTest(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::CLinguistTest)
    , m_languageFlag(true)
    , m_translator(nullptr)
{
    ui->setupUi(this);

    // 创建对话框对象
    m_dialog = new CTipDialog;
    // 连接信号槽,弹出对话框
    connect(ui->showDialogBtn, SIGNAL(clicked()), m_dialog, SLOT(show()));

    // 发出信号,作用为初始化语言
    emit ui->switchLanguageBtn->clicked();
}

CLinguistTest::~CLinguistTest()
{
    delete m_dialog;        // 释放对话框的内存空间
    delete m_translator;    //释放翻译类对象的内存空间
    delete ui;              // 释放ui的内存空 间
}

void CLinguistTest::on_switchLanguageBtn_clicked()
{
    // 当翻译类对象不为空才进入
    if(nullptr != m_translator)
    {
        // 移除上次设置的翻译类对象
        qApp->removeTranslator(m_translator);
        // 释放翻译类对象空间
        delete  m_translator;
    }

    //! 创建时使用默认语言(中文)
    // 获取可执行程序地址,上跳两级目录,再拿到应用程序名,组成项目pro文件所在目录
    QString filePath = qApp->applicationDirPath() + "/../../" +qApp->applicationName();
    // 判断标记值组qm文件地址
    if(m_languageFlag)
    {
        filePath += "/Language/linguist_cn.qm";
    }
    else
    {
        filePath += "/Language/linguist_en.qm";
    }
    // 每次进入将标记值取反
    m_languageFlag = !m_languageFlag;

    // 创建翻译对象
    m_translator = new QTranslator;
    // 加载翻译文件
    m_translator->load(filePath);
    // 安装翻译文件
    qApp->installTranslator(m_translator);

    // 更新翻译
    ui->retranslateUi(this);
    m_dialog->retranslateUi();
}

CLinguistTest.ui

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>CLinguistTest</class>
 <widget class="QMainWindow" name="CLinguistTest">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>290</width>
    <height>280</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>Qt语言家测试</string>
  </property>
  <widget class="QWidget" name="centralWidget">
   <layout class="QVBoxLayout" name="verticalLayout">
    <item>
     <widget class="QLabel" name="label">
      <property name="text">
       <string>一个标签</string>
      </property>
     </widget>
    </item>
    <item>
     <widget class="QCheckBox" name="checkBox">
      <property name="text">
       <string>一个复选框</string>
      </property>
     </widget>
    </item>
    <item>
     <layout class="QHBoxLayout" name="horizontalLayout">
      <item>
       <widget class="QPushButton" name="switchLanguageBtn">
        <property name="text">
         <string>中文</string>
        </property>
       </widget>
      </item>
      <item>
       <widget class="QPushButton" name="showDialogBtn">
        <property name="text">
         <string>弹出一个对话框</string>
        </property>
       </widget>
      </item>
     </layout>
    </item>
    <item>
     <widget class="QTextEdit" name="textEdit">
      <property name="placeholderText">
       <string>我是文本框</string>
      </property>
     </widget>
    </item>
   </layout>
  </widget>
  <widget class="QMenuBar" name="menuBar">
   <property name="geometry">
    <rect>
     <x>0</x>
     <y>0</y>
     <width>290</width>
     <height>23</height>
    </rect>
   </property>
   <widget class="QMenu" name="menumenu">
    <property name="title">
     <string>菜单</string>
    </property>
    <addaction name="action_1"/>
    <addaction name="action_2"/>
   </widget>
   <addaction name="menumenu"/>
  </widget>
  <widget class="QToolBar" name="mainToolBar">
   <attribute name="toolBarArea">
    <enum>TopToolBarArea</enum>
   </attribute>
   <attribute name="toolBarBreak">
    <bool>false</bool>
   </attribute>
  </widget>
  <widget class="QStatusBar" name="statusBar"/>
  <action name="action_1">
   <property name="text">
    <string>选项1</string>
   </property>
  </action>
  <action name="action_2">
   <property name="text">
    <string>选项2</string>
   </property>
  </action>
 </widget>
 <layoutdefault spacing="6" margin="11"/>
 <resources/>
 <connections/>
</ui>

CTipDialog.h

#ifndef CTIPDIALOG_H
#define CTIPDIALOG_H

#include <QDialog>

namespace Ui {
class CTipDialog;
}

class CTipDialog : public QDialog
{
    Q_OBJECT

public:
    explicit CTipDialog(QWidget *parent = nullptr);
    ~CTipDialog();
    /**
     * @brief retranslateUi 调用函数更新翻译
     */
    void retranslateUi();

private:
    Ui::CTipDialog *ui;
};

#endif // CTIPDIALOG_H

CTipDialog.cpp

#include "CTipDialog.h"
#include "ui_CTipDialog.h"
#include <QAbstractButton>

CTipDialog::CTipDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::CTipDialog)
{
    ui->setupUi(this);
}

CTipDialog::~CTipDialog()
{
    delete ui;
}

void CTipDialog::retranslateUi()
{
    // 更新
    ui->retranslateUi(this);
}

CTipDialog.ui

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>CTipDialog</class>
 <widget class="QDialog" name="CTipDialog">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>346</width>
    <height>187</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>提示对话框</string>
  </property>
  <layout class="QVBoxLayout" name="verticalLayout">
   <item>
    <widget class="QLabel" name="label">
     <property name="text">
      <string>一个对话框</string>
     </property>
    </widget>
   </item>
   <item>
    <widget class="QDialogButtonBox" name="buttonBox">
     <property name="orientation">
      <enum>Qt::Horizontal</enum>
     </property>
     <property name="standardButtons">
      <set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>
     </property>
    </widget>
   </item>
  </layout>
 </widget>
 <resources/>
 <connections>
  <connection>
   <sender>buttonBox</sender>
   <signal>accepted()</signal>
   <receiver>CTipDialog</receiver>
   <slot>accept()</slot>
   <hints>
    <hint type="sourcelabel">
     <x>248</x>
     <y>254</y>
    </hint>
    <hint type="destinationlabel">
     <x>157</x>
     <y>274</y>
    </hint>
   </hints>
  </connection>
  <connection>
   <sender>buttonBox</sender>
   <signal>rejected()</signal>
   <receiver>CTipDialog</receiver>
   <slot>reject()</slot>
   <hints>
    <hint type="sourcelabel">
     <x>316</x>
     <y>260</y>
    </hint>
    <hint type="destinationlabel">
     <x>286</x>
     <y>274</y>
    </hint>
   </hints>
  </connection>
 </connections>
</ui>

总结

本文翻译内容都是存在于UI文件中的,UI文件中的文本会自动识别到ts文件中(建议在UI文件中设置窗口标题);要是想代码中操作文本那就需要做其他操作,这就是为什么Qt语言家我打算写多个文章的原因,然后tr函数我个人也需要再搞清楚一点,内容将在(二)中展出。

相关文章

Qt之语言家的简单使用(二)(使用注意事项,含源码+注释)

友情提示——哪里看不懂可私哦,让我们一起互相进步吧
(创作不易,请留下一个免费的赞叭 谢谢 ^o^/)

注:文章为作者编程过程中所遇到的问题和总结,内容仅供参考,若有错误欢迎指出。
注:如有侵权,请联系作者删除

有关Qt之语言家的简单使用(一)(Qt翻译UI,Qt Linguist的使用,含源码+注释)的更多相关文章

  1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

    我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

  2. ruby - 使用 RubyZip 生成 ZIP 文件时设置压缩级别 - 2

    我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看ruby​​zip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d

  3. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  4. ruby-on-rails - 使用 Ruby on Rails 进行自动化测试 - 最佳实践 - 2

    很好奇,就使用ruby​​onrails自动化单元测试而言,你们正在做什么?您是否创建了一个脚本来在cron中运行rake作业并将结果邮寄给您?git中的预提交Hook?只是手动调用?我完全理解测试,但想知道在错误发生之前捕获错误的最佳实践是什么。让我们理所当然地认为测试本身是完美无缺的,并且可以正常工作。下一步是什么以确保他们在正确的时间将可能有害的结果传达给您? 最佳答案 不确定您到底想听什么,但是有几个级别的自动代码库控制:在处理某项功能时,您可以使用类似autotest的内容获得关于哪些有效,哪些无效的即时反馈。要确保您的提

  5. ruby - 在 Ruby 中使用匿名模块 - 2

    假设我做了一个模块如下:m=Module.newdoclassCendend三个问题:除了对m的引用之外,还有什么方法可以访问C和m中的其他内容?我可以在创建匿名模块后为其命名吗(就像我输入“module...”一样)?如何在使用完匿名模块后将其删除,使其定义的常量不再存在? 最佳答案 三个答案:是的,使用ObjectSpace.此代码使c引用你的类(class)C不引用m:c=nilObjectSpace.each_object{|obj|c=objif(Class===objandobj.name=~/::C$/)}当然这取决于

  6. ruby - 使用 ruby​​ 和 savon 的 SOAP 服务 - 2

    我正在尝试使用ruby​​和Savon来使用网络服务。测试服务为http://www.webservicex.net/WS/WSDetails.aspx?WSID=9&CATID=2require'rubygems'require'savon'client=Savon::Client.new"http://www.webservicex.net/stockquote.asmx?WSDL"client.get_quotedo|soap|soap.body={:symbol=>"AAPL"}end返回SOAP异常。检查soap信封,在我看来soap请求没有正确的命名空间。任何人都可以建议我

  7. ruby - i18n Assets 管理/翻译 UI - 2

    我正在使用i18n从头开始​​构建一个多语言网络应用程序,虽然我自己可以处理一大堆yml文件,但我说的语言(非常)有限,最终我想寻求外部帮助帮助。我想知道这里是否有人在使用UI插件/gem(与django上的django-rosetta不同)来处理多个翻译器,其中一些翻译器不愿意或无法处理存储库中的100多个文件,处理语言数据。谢谢&问候,安德拉斯(如果您已经在ruby​​onrails-talk上遇到了这个问题,我们深表歉意) 最佳答案 有一个rails3branchofthetolkgem在github上。您可以通过在Gemfi

  8. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  9. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

    我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

  10. ruby - 使用 ruby​​ 将 HTML 转换为纯文本并维护结构/格式 - 2

    我想将html转换为纯文本。不过,我不想只删除标签,我想智能地保留尽可能多的格式。为插入换行符标签,检测段落并格式化它们等。输入非常简单,通常是格式良好的html(不是整个文档,只是一堆内容,通常没有anchor或图像)。我可以将几个正则表达式放在一起,让我达到80%,但我认为可能有一些现有的解决方案更智能。 最佳答案 首先,不要尝试为此使用正则表达式。很有可能你会想出一个脆弱/脆弱的解决方案,它会随着HTML的变化而崩溃,或者很难管理和维护。您可以使用Nokogiri快速解析HTML并提取文本:require'nokogiri'h

随机推荐