qml local import: either highlited, or works - qt

I had problem when I tried to import local directory qml files( they are in the another prefix in qml.qrc)
import QtQuick 2.0
import QtQuick.Controls 1.3
import QtQuick.Dialogs 1.2
import "Components"
//import "qrc:/Components/QMLs/Components"
Rectangle {
id: mainLocalRect
width: 300
height: 500
color: "orange"
HIcon {
id: hIcon
x: 0
y: 0
}
}
So that, I got error when deploying:
qrc:/QMLs/welcome.qml:4:1: "Components": no such directory
but there is directory Components and in Qt Creator HIcon is highlighted.
https://yadi.sk/i/eF1QKfxEhsdiY
I tried another way to import:
import "qrc:/Components/QMLs/Components"
And its works! But now SideMenu is not highlighted
https://yadi.sk/i/jmdgDZ4dhsdix
Structure of files in project:
main.qml
--QMLs/
----class.qml
----welcome.qml
....
----Components/
------HIcon.qml
Question: How to correctly to import directory?

You can use simply:
import "rel_path"
Where rel_path is the relative path from the point of view of the file that contains the import statement.
As an example, if the component C is in a child directory called D for the parent one, use:
import "../D/"
From now on, you can freely use C within your file.

The reason why highlighting does not work when using the correct qrc import is that QtCreator does not inspect the qrc file.
In addition you have to know how the resource system packages the files. Every file will be packaged with it's relative path to your .qrc file:
main.qml -> qrc:///main.qml
QMLs/welcome.qml -> qrc:///QMLs/welcome.qml
When using prefixes in your resource files those will be prepended to the relative path. (It's not that Qt 'copies' that file into the specified prefix/folder)
In your project that leads to the following situation:
QMLs/Components/SideMenu.qml -> qrc:///Components/QMLs/Components/SideMenu.qml
QMLs/Components/Helpers/MenuBackIcon.qml -> qrc:///Helpers/QMLs/Components/Helpers/MenuBackIcon.qml
It's not only a change in the absolute URL. It also 'moves' the files in the position relative to each other.
Now, to make things better you can specify an alies for each file in your .qrc file. An alias can just be a file name that will be combined with the prefix to make up the full URL:
Let's say you give the alias HIcon for your file QMLs/Components/HIcon.qml. That will lead to the situation that the full URL will be: qrc:///Components/HIcon.qml
Because your .qrc file is in the list of import paths you can now write your code like you'd expect:
import "Components"
[..]
HIcon {
[..]
}
Conclusion / TL;DR
Give each file an alias that is made up of the files name without the path.

Related

Is there a way to use modular css in React TSX? [duplicate]

I opened my old project today and saw these strange warnings:
ERROR in src/App.tsx:13:17
TS2307: Cannot find module './App.module.css' or its corresponding type declarations.
11 | import { Layout, Breadcrumb } from 'antd'
12 | import Header from './components/Header/Header'
> 13 | import css from './App.module.css'
| ^^^^^^^^^^^^^^^^^^
14 | import { ROUTES } from './constants/routes'
15 | import Menu from './components/Menu'
16 |
ERROR in src/components/common/FormsControls/FormsControls.tsx:2:17
TS2307: Cannot find module './FormsControls.module.css' or its corresponding type declarations.
1 | import { FC, MouseEvent } from 'react'
> 2 | import css from './FormsControls.module.css'
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3 | import commonCss from '../styles.module.css'
4 | import { Field, WrappedFieldProps } from 'redux-form'
5 | import cn from 'classnames'
There are also a lot of them with file formats svg, png and others. All my packages are now the most recent version.
There was no such problem before, can anyone help solve this without having to struggle with webpack?
Create a file called declarations.d.ts (you can name it anything you want)
Sometimes it is mandatory to reload your IDE but not always.
// declarations.d.ts
declare module '*.css';
declare module '*.scss';
declare module '*.svg';
// etc ...
TypeScript does not know that there are files other than .ts or .tsx hence it will complain if an import has an unknown file suffix, so in this case, we explicitly tell the compiler that we mean to load a module that can have the following extensions.
In my React app, created with CRA, I had to add in react-app-env.d.ts:
declare module '*.css';
Adding this declaration in separate file, like suggested above, did not work.

Qt QML Settings are not saved/applied

I have simply copied this example from the docs, adjusting the import version number to the newest ones (but I tried with both for same result).
import QtQuick.Window 2.12
import Qt.labs.settings 1.1
Window {
id: window
width: 800
height: 600
Settings {
property alias x: window.x
property alias y: window.y
property alias width: window.width
property alias height: window.height
}
}
As opposed to advertised, the window geometry was not saved after I closed and reopened the window. In fact, it now doesn't show the window at all? (I tried re-running qmake and cleaning all)
I also get this warning every time I run the project in Qt Creator, regardless of whether I use Settings or not:
17:01:02: Starting C:...debug\untitled.exe...
QML debugging is enabled. Only use this in a safe environment.
qrc:/main.qml:10:5: QML Settings: Failed to initialize QSettings instance. Status code is: 1
qrc:/main.qml:10:5: QML Settings: The following application identifiers have not been set: QVector("organizationName", "organizationDomain")
1) Is the warning related to the issue?
2) How do I remove the warning?
3) How do I get the settings to be applied as advertised?
...Turns out I had to keep reading the docs to the end.
1) Warning is related to the issue.
2) Per the docs, add this at the beginning of the main in main.cpp
app.setOrganizationName("Some Company");
app.setOrganizationDomain("somecompany.com");
app.setApplicationName("Amazing Application");
3) Now works as advertised.

What is qmltestrunner?

I have gone through the documentation provided by Qt on TestCase, Qt Quick Test Reference Documentation, Ubuntu QML unit testing, Testing with qmltestrunner part 1 & 2, Writing and running qml testcases, How to create a Qt-Quick Test
All that I have found about it is:
Qmltestrunner is a tool used for unit testing. This tool allows to execute QML files as test cases. These files should contain test_functions. Qmltestrunner is an open-source project and its source code can be found from the github.
But there are few questions for which I'm looking out for answers:
qmltestrunner documentation? where can I find it? (Could not find wiki page for it)
Is qmltestrunner part of qt quick test framework?
What all dependencies are there for qmltestrunner?
Is there any proper example where I can find complete explanation about QML unit testing? qt quick test framework explains running-tests which I couldn't understand.
Thank you
Unfortunately there's no documentation for qmltestrunner (I cannot one). If you only want to know how to use it, qmltestrunner.exe -h may help you. Most options are described in Qt Test Overview.
Yes. Qt Quick Test Reference Documentation - Running Tests says you need a .cpp file that contains QUICK_TEST_MAIN(xxx) and a .pro file that contains CONFIG += qmltestcase, and build this project to run your QML unit tests. The output binary file of this project is (almost the same as) qmltestrunner.
To run qmltestrunner (in Windows with Qt 5.7, for example), you need at least the following modules: Qt5Core.dll, Qt5Gui.dll, Qt5Network.dll, Qt5Qml.dll, Qt5Quick.dll, Qt5QuickTest.dll, Qt5Test.dll, Qt5Widget.dll. And some extra modules for your QML files if needed (ex. QtQuick Controls 2)
TestCase describes how to write a unit tests in QML. To run the file, simply run qmltestrunner.exe -input C:\My\Testing\File\Path\tst_myComponentTest.qml in command line.
Here's simple step-by-step example about how to write a QML component with unit tests. For example, assume that we have a ExpandButton that expands when it is clicked:
//ExpandButton.qml
import QtQuick 2.7
import QtQuick.Controls 1.2
Button {
width: 50; height: 50
onClicked: { width = 100; }
}
To test this behavior, write a tst_ExpandButton.qml:
import QtQuick 2.7
import QtTest 1.0
Item {
width: 800; height: 600
ExpandButton {
id: expandButton
anchors.centerIn: parent
}
TestCase {
name: "ExpandButton"; when: windowShown
function test_clickToExpand() {
var widthBeforeClick = expandButton.width;
mouseClick(expandButton);
var widthAfterClick = expandButton.width;
verify(widthBeforeClick < widthAfterClick);
}
}
}
Now we have two QML files, ExpandButton.qml and tst_ExpandButton.qml. Run the unit test with qmltestrunner.exe -input D:\aaa\bbb\tst_ExpandButton.qml and you can see the result:
********* Start testing of qmltestrunner *********
Config: Using QtTest library 5.7.0, Qt 5.7.0 (i386-little_endian-ilp32 shared (dynamic) release build; by MSVC 2015)
PASS : qmltestrunner::ExpandButton::initTestCase()
PASS : qmltestrunner::ExpandButton::test_clickToExpand()
PASS : qmltestrunner::ExpandButton::cleanupTestCase()
Totals: 3 passed, 0 failed, 0 skipped, 0 blacklisted, 13ms
********* Finished testing of qmltestrunner *********
http://doc.qt.io/qt-5/qtquick-qtquicktest.html This will help in understanding qmltest runner
http://doc.qt.io/qt-5/qml-qttest-signalspy.html This will help in understanding signal spy which is used to catch signals
http://doc.qt.io/qt-5/qml-qttest-testcase.html This will help in writing each test case

How can I set up default startup commands in iPython notebooks?

I want to put couple of cells with commands I need in almost every new notebook in every new notebook I create.
For example when I create a new notebook it should put a
%matplotlib inline
import matplotlib.pyplot as plt
in a cell by default but not execute it.
How could I set something like that up?
This will work for both terminal based IPython shell and Browser based Notebook:
Navigate to ~/.ipython/profile_default
Create a folder called startup if it’s not already there
Add a new Python file called start.py
Put your favorite imports (and custom functions may be) in this file
Launch IPython or a Jupyter Notebook and your favorite libraries will be automatically loaded every time!
Here is my sample for start.py:
Another Source
To define set of commands on default startup, you need to add the commands in the templete ipy_user_conf.py file in your ~/.ipython directory.
This module is imported during IPython startup. So you can easily do : import modules, configure extensions, change options, define magic commands, put variables and functions in the IPython namespace etc.
Here is the sample ipy_user_conf.py :
# Most of your config files and extensions will probably start
# with this import
import IPython.ipapi
ip = IPython.ipapi.get()
# You probably want to uncomment this if you did %upgrade -nolegacy
# import ipy_defaults
import os
def main():
#ip.dbg.debugmode = True
ip.dbg.debug_stack()
# uncomment if you want to get ipython -p sh behaviour
# without having to use command line switches
import ipy_profile_sh
import jobctrl
# Configure your favourite editor?
# Good idea e.g. for %edit os.path.isfile
#import ipy_editors
# Choose one of these:
#ipy_editors.scite()
#ipy_editors.scite('c:/opt/scite/scite.exe')
#ipy_editors.komodo()
#ipy_editors.idle()
# ... or many others, try 'ipy_editors??' after import to see them
# Or roll your own:
#ipy_editors.install_editor("c:/opt/jed +$line $file")
o = ip.options
# An example on how to set options
#o.autocall = 1
o.system_verbose = 0
#import_all("os sys")
#execf('~/_ipython/ns.py')
# -- prompt
# A different, more compact set of prompts from the default ones, that
# always show your current location in the filesystem:
#o.prompt_in1 = r'\C_LightBlue[\C_LightCyan\Y2\C_LightBlue]\C_Normal\n\C_Green|\#>'
#o.prompt_in2 = r'.\D: '
#o.prompt_out = r'[\#] '
# Try one of these color settings if you can't read the text easily
# autoexec is a list of IPython commands to execute on startup
#o.autoexec.append('%colors LightBG')
#o.autoexec.append('%colors NoColor')
o.autoexec.append('%colors Linux')
# some config helper functions you can use
def import_all(modules):
""" Usage: import_all("os sys") """
for m in modules.split():
ip.ex("from %s import *" % m)
def execf(fname):
""" Execute a file in user namespace """
ip.ex('execfile("%s")' % os.path.expanduser(fname))
main()
For more details, please refer the link : Customization of IPython.
I hope this is what you wanted to know.
JupyterLab
In a comment to one of the other answers, the OP pointed out the need to insert the actual code instead of having it load in the background. One way is to create a text keyboard shortcut by going to Settings -> Advanced settings editor -> JSON settings Editor and adding the following under User Preferences:
{
"shortcuts": [
{
"command": "apputils:run-first-enabled",
"selector": "body",
"keys": ["Alt I"],
"args": {
"commands": [
"console:replace-selection",
"fileeditor:replace-selection",
"notebook:replace-selection",
],
"args": {"text": "import pandas as pd\nimport altair as alt\n\n"}
}
}
]
}
This will insert the following snippet each time you press Alt + i in the notebook:
import pandas as pd
import altair as alt
# <-- Cursor placed here
More on text shortcuts in jupyterlab
IPython console
If you are interested in automatically importing commonly used libraries in the IPython console only so that they are there for interactive use, but not in the notebook to avoid issues with sharing notebooks lacking some imports, you can launch IPython like so (and set up an alias to not have to type this each time):
ipython -c "import pandas as pd; import numpy as np" -i
(This was what I was looking for when I originally found this question)

QML Object Type is not a type error in QTCreator

Hi Everyone i am new to QT and i am having trouble loading one qml through another qml
Basically i have created a qml MyTabView(MyTabView.qml)
import QtQuick 2.3
import QtQuick.Controls 1.2
TabView {
width: 360
height: 360
Component.onCompleted: {
addTab("Tab 1", tab1)
addTab("Tab 2", tab2)
}
Component {
id: tab1
Rectangle {color: "red"}
}
Component {
id: tab2
Rectangle {color: "blue"}
}
}
and i am trying to show it through another qml(main.qml) which is in the same directory
import QtQuick 2.3
import QtQuick.Controls 1.2
import "."
ApplicationWindow {
visible: true
width: 640
height: 480
title: qsTr("Main")
MyTabView {}
}
but when i try to run my project i get this error
QQmlApplicationEngine failed to load component
qrc:/qml/main.qml:11 TabView is not a type
Please note that i have M Caps in MyTabView.qml and that MyTabView.qml and main.qml are in the same directory.
Can someone point me what mistake i am doing ?
One thing i want to point is that when i replace all the code of MyTabView.qml instead of MyTabView {} inside main.qml,the program does not give any error and runs correctly.
Thanks in advance
Have you added the file to your Resources ?
Adding your MyTabView.qml to your project in the same directory of main.qml is not sufficient.
You have to put your QML file in the Resources (probably main.qrc/qml/) in order to have it deployed.
The editor of Qt Creator does not need this inclusion in order to find your type, therefore it displays no error.
I had a similar problem.
qrc:AGview.qml:8:15: AGraph is not a type
I solved it:
my original code (in my main.cpp):
view.setSource(QUrl("qrc:AGview.qml"));
the working one:
view.setSource(QUrl("qrc:/AGview.qml"));
I think without the slash it don't search in the actual folder.
You should rename your "TabView.qml" to something like "MyTabView.qml".
Because of that import
import "."
you have conflict of TabView from "QtQuick.Controls 1.2" and local folder "."
This error can also be caused by a component's having an error. For instance, I had this sequence of errors:
QQmlApplicationEngine failed to load component
qrc:/main.qml:6 Type MainView unavailable
qrc:/MainView.qml:27 Type ApplicationLocked unavailable
qrc:/ApplicationLocked.qml:4 MetaStateChart is not a type
It's not very clear, bu the error in MainView is caused by a problem in ApplicationLocked. When I fixed that error, everything else worked.
So contrary to the conventional wisdom of starting with the first compiler error, it may be necessary to start with the last one!
I have the same thing as you, there are 2 solutions, Frist is to lower the qt version below 6, the second is to use cmake to compile, it will be successful
Ok I have had this problem recently with QT 6.2 and QML. Using both CMake and QMake as the build systems.
The solution is to add the QML file e.g. MyTabView.qml to the resources file and make sure it is added to the CMakeLists.txt or the project file (should be done automatically for you).
Then in the top of your main.qml or wherever you are using this custom component import qrc:/. Assuming the custom qml file was added under the prefix / and therefore its resource path will be qrc:/MyTabView.qml.

Resources