QT是支持加载ui文件,并且也支持将ui文件转换为对应的代码,方便用户通过Qt Creator开发好ui,然后直接从Java里调用。
uiLoad方法
ui - ui文件全路径
此方法主要是动态加载ui文件,并且显示,代码如下。
QUiLoader一定要在QApplication.initialize之前初始化
static { loader = new QUiLoader(); }
public QWidget uiLoad(String ui){ QFile file = new QFile(ui); file.open(QIODevice.OpenModeFlag.ReadOnly); QWidget widget = loader.load(file); file.close(); return widget; }
通过这个方法,可以加载任何自定义的ui文件。
uiConvert方法
inputFile - ui文件全路径
outputDir - 生成的java代码目录
targetPackage - 包名
此方法主要是将ui文件,转换为java代码,方便调用。
public void uiConvert(String inputFile, String outputDir, String targetPackage){ Driver driver = new Driver(); QCommandLineParser parser = new QCommandLineParser(); parser.setSingleDashWordOptionMode(QCommandLineParser.SingleDashWordOptionMode.ParseAsLongOptions); parser.addHelpOption(); parser.addVersionOption(); QCommandLineOption postfixOption = new QCommandLineOption("postfix"); postfixOption.setDescription("Postfix to add to all generated classnames."); postfixOption.setValueName("postfix"); parser.addOption(postfixOption); QCommandLineOption translateOption = new QCommandLineOption(QList.of("tr", "translate")); translateOption.setDescription("Use <function> for i18n."); translateOption.setValueName("function"); parser.addOption(translateOption); QCommandLineOption importOption = new QCommandLineOption(QList.of("i", "imports")); importOption.setDescription("Add imports to comma-separated packages and/or classes."); importOption.setValueName("imports"); parser.addOption(importOption); driver.option().postfix = parser.value(postfixOption); driver.option().translateFunction = parser.value(translateOption); driver.option().imports = QDir.fromNativeSeparators(parser.value(importOption)); driver.option().outputDir = QDir.fromNativeSeparators(outputDir); driver.option().targetPackage = targetPackage.contains("/")? targetPackage.replace('/','.'):targetPackage; driver.option().dependencies = true; driver.option().autoConnection = true; driver.option().noShellClass = false; driver.option().forceOutput = true; driver.option().idBased = true; driver.option().forceMemberFnPtrConnectionSyntax = true; driver.option().forceStringConnectionSyntax = true; driver.uic(inputFile, driver.option().outputDir,"java"); }
大家可以根据喜好调整参数,目前的参数是我比较喜欢的,支持C++所有的Qt调用。
当然在Intellij IDEA的终端,也可以用下面的指令进行手动转换。下面2个包,复制到ui文件所在的目录。
java -cp "qtjambi-6.7.1.jar;qtjambi-uic-6.7.1.jar" io.jqt.uic.Main --output=src --package=jui sort.ui
浙公网安备 33010602011771号