PySide - How to connect a signal to a widget that was created through a method being called inside another method - pyside

I'm fairly new to programming so please be patient with me. I'm trying to create a simple script in Autodesk Maya. I've created a method that sets up two check-boxes side by side (See below)...
def checkboxLayout(self, name1, text1, name2, text2, parentLayout, initState):
##create and add horizontal layout
layout = QtGui.QHBoxLayout()
parentLayout.addLayout(layout)
width = 75
name1 = QtGui.QCheckBox(text1)
layout.addWidget(name1)
name1.setMinimumWidth(width)
name1.setMaximumWidth(width)
name1.setChecked(initState)
name2 = QtGui.QCheckBox(text2)
layout.addWidget(name2)
name2.setMinimumWidth(width)
name2.setMaximumWidth(width)
And later on I've called this method twice in order to save me having to write out the same big block of code twice...
def createLayout(self):
##Layout
mainLayout = QtGui.QVBoxLayout()
mainLayout.addWidget(self.title)
mainLayout.addSpacerItem(self.titleSpacer)
mainLayout.addWidget(self.oldLabel)
self.checkboxLayout("selection_CB", "Selection", "name_CB", "Name", mainLayout, True)
mainLayout.addWidget(self.textbox1)
mainLayout.addSpacerItem(self.midSpacer)
mainLayout.addWidget(self.newLabel)
mainLayout.addWidget(self.textbox2)
self.checkboxLayout("delHistory_CB", "Delete\nHistory", "freezeTrans_CB", "Freeze\nTransforms", mainLayout, False)
self.buttonLayout = QtGui.QGridLayout()
mainLayout.addLayout(self.buttonLayout)
self.buttonLayout.addWidget(self.cancelButton, 0, 0)
self.buttonLayout.addWidget(self.okButton, 0, 1)
self.setLayout(mainLayout)
My problem is that when I try to connect a signal to it, it won't work. All the tutorials I've watched so far have only connected signals to widgets that WERE NOT created by calling a method inside another method (I realize that probably isn't the correct terminology but like I said, I'm new to this :( ) I'll post the code that I've written to try and connect the signal below. My guess was that I had to specify the method that created the check box, but I couldn't get that to work either. So how do I get this signal connected? Also feel free to correct my terminology :) Thanks to anyone who can help :)
def createConnections(self):
self.selection_CB.toggled.connect(self.checkboxLine1_ChangeState)

Where and how are you setting the variable self.selection_CB?
In your checkboxLayout function you can include a return for your check box like so:
`return [name1, name2]`
then simply assign them as you're calling the function and connect the events from there:
self.check1, self.check2 = self.checkboxLayout("selection_CB", "Selection", "name_CB", "Name", mainLayout, True)
Or if they are always being connected to the same functions, then why not just do the connection straight from checkboxLayout?
name1.stateChanged.connect(self.checkboxLine1_ChangeState)

Related

PyQGIS, custom processing algorithm: How to use selected features only?

I want to create a custom processing algorithm with PyQGIS, which is able to take a vector layer as input (in this case of type point) and then do something with it's features. It's working well as long as I just choose the whole layer. But it doesn't work if I'm trying to work on selected features only.
I'm using QgsProcessingParameterFeatureSource to be able to work on selected features only. The option is shown and I can enable the checkbox. But when I'm executing the algorithm, I get NoneType as return of parameterAsVectorLayer.
Below you'll find a minimal working example to reproduce the problem:
from qgis.PyQt.QtCore import QCoreApplication
from qgis.core import (
QgsProcessing,
QgsProcessingAlgorithm,
QgsProcessingParameterFeatureSource
)
name = "selectedonly"
display_name = "Selected features only example"
group = "Test"
group_id = "test"
short_help_string = "Minimal working example code for showing my problem."
class ExampleProcessingAlgorithm(QgsProcessingAlgorithm):
def tr(self, string):
return QCoreApplication.translate('Processing', string)
def createInstance(self):
return ExampleProcessingAlgorithm()
def name(self):
return name
def displayName(self):
return self.tr(display_name)
def group(self):
return self.tr(group)
def groupId(self):
return group_id
def shortHelpString(self):
return self.tr(short_help_string)
def initAlgorithm(self, config=None):
self.addParameter(
QgsProcessingParameterFeatureSource(
'INPUT',
self.tr('Some point vector layer.'),
types=[QgsProcessing.TypeVectorPoint]
)
)
def processAlgorithm(self, parameters, context, feedback):
layer = self.parameterAsVectorLayer(
parameters,
'INPUT',
context
)
return {"OUTPUT": layer}
If I'm working on the whole layer, the output is {'OUTPUT': <QgsVectorLayer: 'Neuer Temporärlayer' (memory)>}, which is what I would expect.
If I'm working on selected features only, my output is {'OUTPUT': None}, which doesn't makes sense to me. I selected some of the features before executing of course.
I'm using QGIS-version 3.22 LTR, if it's relevant.
Can anybody tell me what I'm doing wrong?
I would suggest you trying to use the method 'parameterAsSource' in the 'processAlgorithm' method.
layer = self.parameterAsSource(
parameters,
'INPUT',
context
)

Any ar js multimarkers learning tutorial?

I have been searching for ar.js multimarkers tutorial or anything that explains about it. But all I can find is 2 examples, but no tutorials or explanations.
So far, I understand that it requires to learn the pattern or order of the markers, then it stores it in localStorage. This data is used later to display the image.
What I don't understand, is how this "learner" is implemented. Also, the learning process is only used once by the "creator", right? The output file should be stored and then served later when needed, not created from scratch at each person's phone or computer.
Any help is appreciated.
Since the question is mostly about the learner page, I'll try to break it down as much as i can:
1) You need to have an array of {type, URL} objects.
A sample of creating the default array is shown below (source code):
var markersControlsParameters = [
{
type : 'pattern',
patternUrl : 'examples/marker-training/examples/pattern-files/pattern-hiro.patt',
},
{
type : 'pattern',
patternUrl : 'examples/marker-training/examples/pattern-files/pattern-kanji.patt',
}]
2) You need to feed this to the 'learner' object.
By default the above object is being encoded into the url (source) and then decoded by the learner site. What is important, happens on the site:
for each object in the array, an ArMarkerControls object is created and stored:
// array.forEach(function(markerParams){
var markerRoot = new THREE.Group()
scene.add(markerRoot)
// create markerControls for our markerRoot
var markerControls = new THREEx.ArMarkerControls(arToolkitContext, markerRoot, markerParams)
subMarkersControls.push(markerControls)
The subMarkersControls is used to create the object used to do the learning. At long last:
var multiMarkerLearning = new THREEx.ArMultiMakersLearning(arToolkitContext, subMarkersControls)
The example learner site has multiple utility functions, but as far as i know, the most important here are the ArMultiMakersLearning members which can be used in the following order (or any other):
// this method resets previously collected statistics
multiMarkerLearning.resetStats()
// this member flag enables data collection
multiMarkerLearning.enabled = true
// this member flag stops data collection
multiMarkerLearning.enabled = false
// To obtain the 'learned' data, simply call .toJSON()
var jsonString = multiMarkerLearning.toJSON()
Thats all. If you store the jsonString as
localStorage.setItem('ARjsMultiMarkerFile', jsonString);
then it will be used as the default multimarker file later on. If you want a custom name or more areas - then you'll have to modify the name in the source code.
3) 2.1.4 debugUI
It seems that the debug UI is broken - the UI buttons do exist but are nowhere to be seen. A hot fix would be using the 'markersAreaEnabled' span style for the div
containing the buttons (see this source bit).
It's all in this glitch, you can find it under the phrase 'CHANGES HERE' in the arjs code.

How to use polymorphism to remove a switch statement which compares strings?

I am new to Ruby, so let me describe the context of my problem first:
I have a json as input which has the following key / value pair:
{
"service": "update"
}
The value has many different values for example: insert,delete etc.
Next there is a method x which handles the different requests:
def x(input)
case input[:service]
services = GenericService.new
when "update"
result = services.service(UpdateService.new,input)
when "insert"
result = services.service(InsertService.new,input)
when "delete"
result = services.service(DeleteService.new,input)
....
....
else
raise "Unknown service"
end
puts JSON.pretty_generate(result)
end
What is bothering me is that I still need to use a switch statement to check the String values (reminds me of 'instance of' ugh..). Is there a cleaner way (not need to use a switch)?
Finally I tried to search for an answer to my question and did not succeed, if however I missed it feel free to comment the related question.
Update: I was thinking to maybe cast the string to the related class name as follows: How do I create a class instance from a string name in ruby? and then call result = services.services(x.constantize.new,input) , then the class names ofcourse needs to match the input of the json.
You can try something like:
def x(input)
service_class_name = "#{input[:service].capitalize}Service"
service_class = Kernel.const_get(service_class_name)
service_class.new(input).process
end
In addition you might want to check if this is a valid Service class name at all.
I don't understand why you want to pass the service to GenericService this seems strange. let the service do it's job.
If you're trying to instatiate a class by it's name you're actually speaking about Reflection rather than Polymorphism.
In Ruby you can achieve this in this way:
byName = Object.const_get('YourClassName')
or if you are in a Rails app
byName= 'YourClassName'.constantize
Hope this helps
Just first thoughts, but you can do:
eval(services.service("#{input[:service].capitalize}Service.new, #{input})") if valid_service? input[:service]
def valid_service?
w%(delete update insert).include? input[:service]
end
As folks will no doubt shout, eval needs to be used with alot of care

Qt GUI Table / Spreadsheet type layout in Ruby

I am trying to design a GUI that will output data in a spreadsheet type of format, rows and columns.
The cells will be populated with data that will be fetched by another object at predefined intervals. Being able to change individual cell color would be ideal to highlight any cells that have changed.
After some research it seems like QtBindings gem for ruby is the most powerful GUI choice for this but I can't seem to find any documentation or examples that would help me with what I am trying to accomplish. Any advice in the form of code or examples would be more than helpful. Thank you.
Update:: after some research and brute force, I came up with this code:
class PositionModel < Qt::AbstractTableModel
slots 'timerhit()'
def initialize(risk)
super()
#timer = Qt::Timer.new(self)
connect(#timer, SIGNAL('timeout()'), self, SLOT('timerhit()'))
#timer.start(1000)
#risk = risk
#risk_a = #risk.to_a
#pp #risk_a
end
def timerhit()
emit dataChanged(createIndex(0,0), createIndex(0,0))
#emit dataChanged()
end
def rowCount(parent)
#risk_a.size
end
def columnCount(parent)
1
end
def data(index, role)
col = index.column
row = index.row
if role == Qt::DisplayRole
return Qt::Variant.new( #risk_a[row] )
else
return Qt::Variant.new()
end
end
end
app = Qt::Application.new(ARGV)
model = PositionModel.new(##risk)
table = Qt::TableView.new
table.model = model
table.setSortingEnabled(true)
table.show
It seems to be working well, and more importantly is a solid foundation for what I ultimately want to accomplish. However, I I tried to enable sorting by clicking on a column header, but it doesnt seem to be working. Does anyone know why?
Two words: Use QTableView or QTableWidget.
Populating Table Widget from Text File in Qt
How change row color with Null items?
Converting the c++ code to ruby qt should be trivial. Also the C++ Qt docs are awesome! Good luck.
Hope that helps.

Tkinter Error when using Entry Delete Method

In my game, I have an __init__ function which creates a set of seven entry boxes, like so:
self.string1 = StringVal()
self.entry1 = Entry(frame, textvariable = self.string1).grid(row = 4, column = 1, sticky = W)
This is copied six more times. This works.
At the end of the game, though, I want to delete the Entry box's text, using this code I found several places online:
self.entry1.delete(0, END)
I also tried using something else I found:
if self.entry1.get():
self.entry1.delete(0, END)
These both say that self.entry1 is a NoneType object, and has no method .get() or .delete(). Just to try things out, I substituted self.entry1.get() and self.entry1.delete(0,END) with self.string1.get(), etc. I also tried substituting .delete(0, END) with .delete(0.0, END). Neither of these worked either. I do not understand what I am doing wrong.
Thanks for your help!
When you do something like this:
self.foo = Button(...).grid(...)
... Then what gets stored in self.foo is the result of the call to grid(). This will always be None. You need to separate your widget creation from the loyout in order to save a reference to the created widgets.

Resources