QML iterating through model - qml

I am trying to draw the content of a ListModel to a canvas in QML. The content of this model is displayed in a ListView elsewhere in the application, so I know the model is correctly filled with content.
No I am trying to update the canvas every time the model data changes:
import QtQuick 2.7
import QtQml.Models 2.2
Item {
Canvas {
anchors.fill: parent
id: canvas
onPaint: {
console.log("onPaint()")
var ctx = getContext("2d")
ctx.fillStyle = Qt.rgba(0, 0, 0, 1)
ctx.fillRect(0, 0, width, height)
console.log(particleListModel.count)
for(var i = 0; i < particleListModel.count; i++) {
console.log(i)
}
}
}
Connections {
target: particleListModel
onDataChanged: {
console.log("data changed")
canvas.requestPaint()
}
}
}
Once I change the data (in C++) I receive the dataChanged() signal and the onPaint() of the canvas gets called. However the debug output of
console.log(particleListModel.count)
is "undefined".
How can this be, while the regular ListView is able to display the content correctly?

When working with the Model you need to call the rowCount function instead of count since the latter is a property of the ListView and not of the model.
The following should work:
console.log(particleListModel.rowCount())

Related

SwiftUI ScrollView to PDF

Currently, I am using this code to create a PDF, but it only creates a PDF of the part of the page the user is looking at, and not the entire scroll view. How can I create a multi-page PDF to get the entire scroll view?
func exportToPDF(width:CGFloat, height:CGFloat, airplane: String, completion: #escaping (String) -> Void) {
let documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let outputFileURL = documentDirectory.appendingPathComponent("smartsheet-\(airplane.afterchar(first: "N")).pdf")
//Normal with
let width: CGFloat = width
//Estimate the height of your view
let height: CGFloat = height
let charts = SmartSheet().environmentObject(Variables())
let pdfVC = UIHostingController(rootView: charts)
pdfVC.view.frame = CGRect(x: 0, y: 0, width: width, height: height)
//Render the view behind all other views
let rootVC = UIApplication.shared.windows.first?.rootViewController
rootVC?.addChild(pdfVC)
rootVC?.view.insertSubview(pdfVC.view, at: 0)
//Render the PDF
let pdfRenderer = UIGraphicsPDFRenderer(bounds: CGRect(x: 0, y: 0, width: width, height: height))
DispatchQueue.main.async {
do {
try pdfRenderer.writePDF(to: outputFileURL, withActions: { (context) in
context.beginPage()
rootVC?.view.layer.render(in: context.cgContext)
})
UserDefaults.standard.set(outputFileURL, forKey: "pdf")
UserDefaults.standard.synchronize()
print("wrote file to: \(outputFileURL.path)")
completion(outputFileURL.path)
} catch {
print("Could not create PDF file: \(error.localizedDescription)")
}
pdfVC.removeFromParent()
pdfVC.view.removeFromSuperview()
}
}
I just posted this answer to another question as well.
https://stackoverflow.com/a/74033480/14076779
After attempting a number of solutions to creating a pdf from a SwiftUI ScrollView and landed on this implementation. It is by no means an implementation that is pretty, but it seems to work.
M use case is that I present a modal to capture a user's signature and when the signature is collected, the content of the current screen is captured. There is no pagination, just a capture of the content currently rendered to the width of the screen and as much length as is required by the view.
The content consists of an array of cards that are dynamically generated, so the view has no awareness of the content and cannot calculate the height. I have not tested on a list, but I imagine it would provide similar results.
struct SummaryTabView: View {
// MARK: View Model
#ObservedObject var viewModel: SummaryTabViewModel
// MARK: States and Bindings
#State private var contentSize: CGSize = .zero // Updated when the size preference key for the overlay changes
#State private var contentSizeForPDF: CGSize = .zero // Set to match the content size when the signature modal is displayed.
// MARK: Initialization
init(viewModel: SummaryTabViewModel) {
self.viewModel = viewModel
}
// MARK: View Body
var body: some View {
ScrollView {
content
.background(Color.gray)
// Placing the a geometry reader in the overlay here seems to work better than doing so in a background and updates the size value for the size preference key.
.overlay(
GeometryReader { proxy in
Color.clear.preference(key: SizePreferenceKey.self,
value: proxy.size)
}
)
}
.onPreferenceChange(SizePreferenceKey.self) {
// This keeps the content size up-to-date during changes to the content including rotating.
contentSize = $0
}
// There are issues with the sizing the content when the orientation changes and a modal view is open such as when collecting the signature. If the iPad is rotated when the modal is open, then the content size is not being set properly. To avoid this, when the user opens the modal for signing, the content size for PDF generation is set to the current value since the signature placeholder is already present so the content size will not change.
.onReceive(NotificationCenter.default.publisher(for: .openingSignatureModal)) { _ in
self.contentSizeForPDF = contentSize
}
}
// MARK: Subviews
var header: SceneHeaderView {
SceneHeaderView(viewModel: viewModel)
}
// Extracting this view into a variable allows grabbing the screenshot when the customer signature is collected.
var content: some View {
LazyVStack(spacing: 16) {
header
ForEach(viewModel.cardViewModels) { cardViewModel in
// Each card needs to be in a VStack with no spacing or it will end up having a gap between the header and the card body.
VStack(spacing: 0) {
UICardView(viewModel: cardViewModel)
}
}
}
.onReceive(viewModel.signaturePublisher) {
saveSnapshot(content: content, size: contentSizeForPDF)
}
}
// MARK: View Functions
/// Creates and saves a pdf data file to the inspection's report property. This is done asynchronously to avoid odd behavior with the graphics renering process.
private func saveSnapshot<Content: View>(content: Content, size: CGSize) {
let pdf = content
.frame(width: size.width, height: size.height)
.padding(.bottom, .standardEdgeSpacing) // Not sure why this padding needs to be added but for some reason without it the pdf is tight to the last card on the bottom. It appears that extra padding is being added above the header, but not sure why.
.toPDF(format: self.pdfFormat)
self.saveReport(data: pdf)
}
private var pdfFormat: UIGraphicsPDFRendererFormat {
let format = UIGraphicsPDFRendererFormat()
// TODO: Add Author here
let metadata = [kCGPDFContextCreator: "Mike",
kCGPDFContextAuthor: viewModel.userService.userFullName]
format.documentInfo = metadata as Dictionary<String, Any>
return format
}
private func saveReport(data: Data?) {
guard let data = data else {
log.error("No data generated for pdf.")
return
}
do {
try viewModel.saveReport(data)
print("Report generated for inspection")
} catch {
print("Failed to create pdf report due to error: \(error)")
}
// Used to verify report in simulator
let documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
var filename = "\(UUID().uuidString.prefix(6)).pdf"
let bodyPath = documentDirectory.appendingPathComponent(filename)
do {
let value: Data? = viewModel.savedReport
try value?.write(to: bodyPath)
print("pdf directory: \(documentDirectory)")
} catch {
print("report not generated")
}
}
// MARK: Size Preference Key
private struct SizePreferenceKey: PreferenceKey {
static var defaultValue: CGSize = .zero
static func reduce(value: inout CGSize, nextValue: () -> CGSize) {
value = nextValue()
}
}
}
// MARK: Get image from SwiftUI View
extension View {
func snapshot() -> UIImage {
let controller = UIHostingController(rootView: self)
let view = controller.view
let targetSize = controller.view.intrinsicContentSize
view?.bounds = CGRect(origin: .zero, size: targetSize)
view?.backgroundColor = .clear
let renderer = UIGraphicsImageRenderer(size: targetSize)
return renderer.image { _ in
view?.drawHierarchy(in: controller.view.bounds, afterScreenUpdates: true)
}
}
func toPDF(format: UIGraphicsPDFRendererFormat) -> Data {
let controller = UIHostingController(rootView: self)
let view = controller.view
let contentSize = controller.view.intrinsicContentSize
view?.bounds = CGRect(origin: .zero, size: contentSize)
view?.backgroundColor = .clear
let renderer = UIGraphicsPDFRenderer(bounds: controller.view.bounds, format: format)
return renderer.pdfData { context in
context.beginPage()
view?.drawHierarchy(in: controller.view.bounds, afterScreenUpdates: true)
}
}
}
I landed on using a size preference key because a lot of other options did not perform as expected. For instance, setting the content size in .onAppear ended up yielding a pdf with a lot of space above and below it. At one point I was creating the pdf using a boolean state that when changed would use the geometry reader's current geometry. That generally worked, but would provide unexpected results when the user would rotate the device while a modal was open.
References (as best I can recall):
SizePreferenceKey: https://swiftwithmajid.com/2020/01/15/the-magic-of-view-preferences-in-swiftui/
Snapshot View extension: https://www.hackingwithswift.com/quick-start/swiftui/how-to-convert-a-swiftui-view-to-an-image

How to update the map properly using canvas and a button when the players relocate to a new location?

My game snapshot Attachment> Blockquote
My canvas constructs
public class DrawingView4 extends View{
DrawingView4(Context context4)
{
super(context4);
}
#Override protected void onDraw(Canvas canvas4)
{
int tile4=0;
if (DoneDrawFacilities && doneloading) {
}
else {
for (int i4=0; i4< 17 && notfixingorientation; i4++){
if (i4< 16) {
for (int ii4=0; ii4 < 16; ii4++){
try {
//Checking the data of all spots of the game map from package directory.
//Then Draw in canvas if the data of the spot occupied by type of human and core facilities,
FacilityList = new Gson().fromJson(FileUtil.readFile(FileUtil.getPackageDataDir(getApplicationContext()).concat("/GameResource/Tile".concat(String.valueOf((long)(tile4 + 1)).concat(".data")))), new TypeToken<ArrayList<HashMap<String, Object>>>(){}.getType());
if (FacilityList.get((int)0).get("Type").toString().equals("Human")) {
canvas4.drawBitmap(BitmapFactory.decodeFile(AllObjects.getString(String.valueOf((long)(tile4)), "")),null,new Rect(ii4*120, i4*120, 120*(ii4+1),120*(i4+1)), null);
}
if (FacilityList.get((int)0).get("Type").toString().equals("Core")) {
if (FacilityList.get((int)0).get("Name").toString().equals("Arena")) {
canvas4.drawBitmap(BitmapFactory.decodeFile(AllObjects.getString(String.valueOf((long)(tile4)), "")),null,new Rect(7*120, 7*120, 120*(8+1),120*(8+1)), null);
}
else {
}
}
} catch (Exception e) {
}
FacilityList.clear();
tile4++;
}
}
else {
DoneDrawFacilities = true;
}
}
}
}}
Blockquote
My Relocate button
//I use sharepreference called AllObjects rather than a list and I Only update the path of objects in specific tile in sharedpreference such as in variable 1, 2, etc. and then re-draw using this code below, next time I update the objects path and get this object path from the same json file in the package directory. Too decode to Bitmap and then Draw in canvas.
//Some other code are removed that just updating some data in specific file directory.
AA_structures_facilities.removeAllViews();
AA_structures_facilities.addView(new DrawingView4(GameActivity.this));
// But It freezes the screen or stop me from touching the touch event in a second everytime I update new canvas.
//WHILE MY touchevent is hundled in the parent LinearLayout where the canvas is placed.

How to update ItemFragment when item property changes

I'm quite confused about the relationship between an ItemViewModel and its underlying item. I'm trying to show a badge on the screen, and then if the badge is "achieved" on another thread, the badge should update on screen.
Right now, the badge code looks like this:
class Badge {
val achievedProperty = SimpleBooleanProperty(this, "achieved", false)
var achieved by achievedProperty
}
class BadgeModel: ItemViewModel<Badge>() {
val achieved = bind(Badge::achievedProperty)
}
Next, I want to display it on the screen, in an ItemFragment subclass:
class BadgeFragment(badge: Badge): ItemFragment<Badge>() {
private val model: BadgeModel by inject()
init {
model.item = badge
}
override val root = rectangle {
width = 50
height = 50
stroke = Color.BLACK
fill = if (model.achieved) Color.RED else Color.GREEN
}
}
This works fine to start, but if I then set badge.achieved = true (in my controller), the color of the badge on screen doesn't change.
I'm clearly missing something about the relationship between the object and the model, but I'm having a lot of trouble figuring it out from documentation. Can someone help me get my fragment working the way I want it to?
Your problem isn't specific to models or almost anything TornadoFX-related. The way you've written it only checks for the color once upon creation. You need to use properties or bindings to listen to property changes:
class Test : Fragment() {
val modelAchieved = SimpleBooleanProperty(true) // pretend this is model.achieved
val achievedColor = modelAchieved.objectBinding { isAchieved ->
if (isAchieved == true) Color.RED
else Color.GREEN
}
override val root = vbox {
togglebutton("Toggle") {
selectedProperty().bindBidirectional(modelAchieved)
}
rectangle(width = 50, height = 50) {
stroke = Color.BLACK
fillProperty().bind(achievedColor)
}
}
}
I would also bidirectionally bind the item properties of the viewmodel and fragment together so they stay in sync. Or just use a regular fragment, and reference the model's item property by itself.

How to draw some text when click a button in wxWidgets?

I want to draw some text when click a button. My code is:
#include <wx/wx.h>
enum
{
BUTTON_Hello = wxID_HIGHEST + 1
};
class myFrame : public wxFrame {
public:
wxButton* HelloWorld;
wxPanel* panel;
void OnPaint(wxCommandEvent& event) {
wxClientDC bdc =wxClientDC(this);
bdc.DrawText(wxString("Draw some text when button clicked."), wxPoint(300, 300));
Refresh();
};
myFrame(wxWindow* parent,
wxWindowID id,
const wxString& title,
const wxPoint& pos = wxDefaultPosition,
const wxSize& size = wxDefaultSize) :
wxFrame(parent,id,title, pos, size) {
panel =new wxPanel(this, wxID_ANY, wxPoint(0,0),wxSize(100,100));
//Connect(wxEVT_PAINT, wxPaintEventHandler(myFrame::OnPaint));
HelloWorld = new wxButton(panel, BUTTON_Hello, _T("Hello World"),
wxPoint(5,5), wxSize(100, 100));
HelloWorld->Bind(wxEVT_BUTTON, &myFrame::OnPaint, this);
};
};
class MyApp : public wxApp
{
bool OnInit() {
frame = new myFrame((wxFrame*)NULL, -1, wxT("Hello wxDC"),
wxPoint(50, 50), wxSize(800, 600));
frame->Show();
return true;
};
wxFrame* frame;
public:
};
IMPLEMENT_APP(MyApp)
I define the drawing function in a wxFrame and bind it to a wxButton using Bind(). The drawing function uses a wxClientDC. I have added Refersh() to force updating wxFrame. The wxButton belongs to a wxPanel which is a child of wxFrame.
However, when I click the button, nothing happens and no text is shown.
You must use wxPaintDC when drawing in your wxEVT_PAINT handler, not wxClientDC. While wxClientDC also "works", at least for now and at least under some platforms, this is definitely not the right way to do it.
When using wxPaintDC, Refresh() would work as expected and will result in a call to your paint handler during the next event loop iteration. Normally you don't need to call Update(), which immediately calls your handler, at all.
I solved this problem by myself.
As wxPanel is the only child of wxFrame, it will automatically cover the whole area of wxFrame. Now drawing on wxFrame is necessarily having no effect. So I have to draw on wxPanel:
void paintNow(wxCommandEvent& event) {
wxClientDC bdc =wxClientDC(panel);
bdc.DrawText(wxString("Draw some texts when button clicked."),
wxPoint(300, 300));
//panel->Refresh();
panel->Update();
};
Also I find that if I use Refresh() and Update() simultaneously, no text will be shown.
If I only use Refresh(), no text will be shown.

How to add css style to custom image node in JavaScript InfoVis ToolKit

I have created custom nodes for my force directed InfoVis graph in which I display a user's image. I want to now add style to the image, such as adding a border and making it a circle. I tried adding css class as follows, but it's not working.
img.className = myClass;
here's my custom node code:
//Custom nodes
$jit.ForceDirected.Plot.NodeTypes.implement({
'customImage':
{
'render': function (node, canvas)
{
var ctx = canvas.getCtx();
var img = new Image();
var pos = node.getPos();
img.onload = function ()
{
ctx.drawImage(img, pos.x - 16, pos.y - 16);
}
var n = _nodes[node.id];
if (n && n.imageUrl)
{
var size = 52;
var url = n.imageUrl.replace("{width}", size).replace("{height}", size);
img.src = url;
img.className = myClass;
}
else
{
img.src = '../Images/UserNoImage.png';
}
},
'contains': function (node, pos)
{
var npos = node.pos.getc(true),
dim = node.getData('dim');
return this.nodeHelper.square.contains(npos, pos, dim);
}
}
});
You can apply CSS styles to the html elements. The custom node which you have defined is simply drawing image on the canvas. The node does not correspond to any html element.
Hence before you call function drawImage you should make sure that the image is customized to your requirement, only then you call drawImage. In this case infovis does not know anything about css, all that it does is call drawImage which simply draws an image on the canvas.
Thus, the question you should tackle is, how do you apply css to the image so that its customized to your requirement. And this question is independent of infovis.