I have a form in QML with two TextFields. How do I access the value entered in the fields in Python?
I'm using PyQt5.5 and Python3.
import sys
from PyQt5.QtCore import QObject, QUrl
from PyQt5.QtWidgets import QApplication
from PyQt5.QtQuick import QQuickView
from PyQt5.QtQml import QQmlApplicationEngine
if __name__ == '__main__':
myApp = QApplication(sys.argv)
engine = QQmlApplicationEngine()
context = engine.rootContext()
context.setContextProperty("main", engine)
engine.load('basic.qml')
win = engine.rootObjects()[0]
button = win.findChild(QObject, "myButton")
def myFunction():
print("handler called")
foo = win.findChild(QObject, "login")
print(dir(foo))
print(foo.text)
button.clicked.connect(myFunction)
win.show()
sys.exit(myApp.exec_())
basic.qml
import QtQuick 2.3
import QtQuick.Controls 1.2
ApplicationWindow {
width: 250; height: 175
Column {
spacing: 20
TextField {
objectName: "login"
placeholderText: qsTr("Login")
focus: true
}
TextField {
placeholderText: qsTr("Password")
echoMode: TextInput.Password
}
Button {
signal messageRequired
objectName: "myButton"
text: "Login"
onClicked: messageRequired()
}
}
}
Console
Traceback (most recent call last):
File "working.py", line 25, in myFunction
print(foo.text)
AttributeError: 'QQuickItem' object has no attribute 'text'
fish: “python working.py” terminated by signal SIGABRT (Abort)
You need to call the property() method of the object to get the desired property.
In your example, you need to call:
print(foo.property("text"))
rather than print(foo.text)
Note that property() returns None if the property doesn't exists.
Related
I have a GitBlit instance on a windows server, and i want to set a hook on post receive callback to start a gitlab ci pipeline on another server.
I already have set a GitlabCi trigger who works well, but my hook doesn't. Here is build-gitlab-ci.groovy file :
import com.gitblit.GitBlit
import com.gitblit.Keys
import com.gitblit.models.RepositoryModel
import com.gitblit.models.UserModel
import com.gitblit.utils.JGitUtils
import org.eclipse.jgit.lib.Repository
import org.eclipse.jgit.revwalk.RevCommit
import org.eclipse.jgit.transport.ReceiveCommand
import org.eclipse.jgit.transport.ReceiveCommand.Result
import org.slf4j.Logger
logger.info("Gitlab-CI hook triggered by ${user.username} for ${repository.name}")
// POST :
def sendPostRequest(urlString, paramString) {
def url = new URL(urlString)
def conn = url.openConnection()
conn.setDoOutput(true)
def writer = new OutputStreamWriter(conn.getOutputStream())
writer.write(paramString)
writer.flush()
String line
def reader = new BufferedReader(new InputStreamReader(conn.getInputStream()))
while ((line = reader.readLine()) != null) {
println line
}
writer.close()
reader.close()
}
sendPostRequest("https://xxxxx/api/v4/projects/1/trigger/pipeline", "token=xxxxxxxx&ref=master")
The project configuration :
Moreover, i don't know where logger.info write the log, so i don't know if my script was executed well. Thanks for help
I found my problem, it was a SSL self-certificate problem. I added this code to ignore it :
import com.gitblit.GitBlit
import com.gitblit.Keys
import com.gitblit.models.RepositoryModel
import com.gitblit.models.UserModel
import com.gitblit.utils.JGitUtils
import org.eclipse.jgit.lib.Repository
import org.eclipse.jgit.revwalk.RevCommit
import org.eclipse.jgit.transport.ReceiveCommand
import org.eclipse.jgit.transport.ReceiveCommand.Result
import org.slf4j.Logger
logger.info("Gitlab-CI hook triggered by ${user.username} for ${repository.name}")
def nullTrustManager = [
checkClientTrusted: { chain, authType -> },
checkServerTrusted: { chain, authType -> },
getAcceptedIssuers: { null }
]
def nullHostnameVerifier = [
verify: { hostname, session -> hostname.startsWith('yuml.me')}
]
javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL")
sc.init(null, [nullTrustManager as javax.net.ssl.X509TrustManager] as javax.net.ssl.X509TrustManager[], null)
javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory())
javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(nullHostnameVerifier as javax.net.ssl.HostnameVerifier)
def url = new URL("https://xxxx/api/v4/projects/{idProject}/trigger/pipeline")
def conn = url.openConnection()
conn.setDoOutput(true)
def writer = new OutputStreamWriter(conn.getOutputStream())
writer.write("token={token}&ref={branch}")
writer.flush()
String line
def reader = new BufferedReader(new InputStreamReader(conn.getInputStream()))
while ((line = reader.readLine()) != null) {
println line
}
writer.close()
reader.close()
And I identified the error checking the logs in E:\gitblit-1.7.1\logs\gitblit-stdout.{date}.log.
NB : stdout file date can be very old. Gitblit doesn't create a file per day. Mine had a name expired 4 months ago.
Please help. I can't understand whats wrong with my script.
import org.apache.log4j.Category
import com.atlassian.jira.ComponentManager
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.jql.builder.JqlQueryBuilder
import com.atlassian.jira.event.type.EventDispatchOption
import com.atlassian.jira.issue.MutableIssue
import java.util.Date
import java.util.Calendar
import com.atlassian.jira.bc.JiraServiceContextImpl
import com.atlassian.jira.web.bean.PagerFilter
import com.atlassian.jira.issue.Issue
import java.util.List
import com.atlassian.jira.issue.IssueInputParameters
import com.atlassian.jira.user.util.UserManager
import com.atlassian.jira.user.ApplicationUser
import com.atlassian.crowd.embedded.api.CrowdService
import com.atlassian.crowd.embedded.api.User
def Category log = Category.getInstance("com.onresolve.jira.groovy.PostFunction")
log.setLevel(org.apache.log4j.Level.DEBUG)
def user = ComponentAccessor.getJiraAuthenticationContext().getLoggedInUser()
def ctx = new JiraServiceContextImpl(user)
def searchRequestService = ComponentManager.getInstance().getSearchRequestService()
def searchProvider = ComponentManager.getInstance().getSearchProvider()
def sr = searchRequestService.getFilter(ctx, 17540)
def searchResult = searchProvider.search(sr?.getQuery(), user, PagerFilter.getUnlimitedFilter())
def issueManager = ComponentManager.getInstance().getIssueManager()
def issues = searchResult.getIssues().collect {issueManager.getIssueObject(it.id)}
for ( issue in issues ){
issueInputParameters issueToCreate = ComponentAccessor.getIssueService().newIssueInputParameters();
issueToCreate.setSummary("This is a test.");
issueToCreate.setDescription("Testing issue creation");
issueToCreate.setAssigneeId(user.getName());
issueService.createValidationResult validationResult = ComponentAccessor.getIssueService().validateCreate(user, issueToCreate);
if(!validationResult.isValid()){
for(String registeredErrorMessage:validationResult.getErrorCollection().getErrors().values())
{
printx "Failed"
}
}
else {
issueService.issueResult createdIssue = ComponentAccessor.getIssueService().create(user, validationResult);
}
}
return issues
I get the next excetpion :
groovy.lang.MissingMethodException: No signature of method:
org.codehaus.groovy.jsr223.GroovyScriptEngineImpl.issueInputParameters()
is applicable for argument types:
(com.atlassian.jira.issue.IssueInputParametersImpl) values:
[com.atlassian.jira.issue.IssueInputParametersImpl#6cde0354] at
Script87.run(Script87.groovy:34)
Thank you.
Shouldn't the issueInputParameters in this line be capitialized - IssueInputParameters:
issueInputParameters issueToCreate = ComponentAccessor.getIssueService().newIssueInputParameters();
Why does this code fail ?
I want to change the color of one panel in a series of several panels, dynamically constructed (total number of panels not known beforehand).
For some reason, this code works when referencing the name of a particular panel (for example 'panel2'), but not when I refer to it dynamically ('panelID').
import groovy.swing.SwingBuilder
import javax.swing.WindowConstants as WC
import javax.swing.JOptionPane
import javax.swing.BoxLayout as BXL
swing = new SwingBuilder()
frame = swing.frame(title:'test',
defaultCloseOperation:WC.DISPOSE_ON_CLOSE) {
panel(id:'mainPanel'){
def panelID
(1..6).each {
panelID = 'panel' + it
panel(alignmentX: 0f, id: panelID , opaque:true ,background : java.awt.Color.GREEN){
label('description')
textField(id: "description$it", text: panelID, columns: 70 )
button(id: "button$panelID", text: panelID, actionPerformed : {
panelID.background = java.awt.Color.RED
panelID.repaint()
})
}
}
boxLayout(axis: BXL.Y_AXIS)
panel(id:'secondPanel' , alignmentX: 0f){
button('Quit', actionPerformed:{
dispose()
})
}
}
}
frame.pack()
frame.show()
To get the element based on it's ID, you need to access the ID as a parameter of the SwingBuilder, like so:
import groovy.swing.SwingBuilder
import javax.swing.WindowConstants as WC
import javax.swing.JOptionPane
import javax.swing.BoxLayout as BXL
swing = new SwingBuilder()
frame = swing.frame(title:'test', pack:true, visible:true, defaultCloseOperation:WC.DISPOSE_ON_CLOSE) {
panel(id:'mainPanel'){
(1..6).each { num ->
def panelID = "panel$num"
def pane = panel( alignmentX:0f, id:panelID, background:java.awt.Color.GREEN ) {
label('description')
textField(id: "description$num", text:panelID, columns: 70 )
button(id: "buttonpanel$num", text:panelID, actionPerformed : {
swing."$panelID".background = java.awt.Color.RED
})
}
}
boxLayout(axis: BXL.Y_AXIS)
panel(id:'secondPanel' , alignmentX: 0f){
button('Quit', actionPerformed:{
frame.visible = false
})
}
}
}
I have run the following code in this page RsyntaxTextArea using Java and i run the program exactly the way that is been mentioned in this site.And i'm getting the output as intended. But i have tried to modify this java code to Groovy code, something like:
import groovy.swing.SwingBuilder
import javax.swing.*
import java.awt.*
swing = new SwingBuilder()
frame = swing.frame(title : "test", defaultCloseOperation:JFrame.EXIT_ON_CLOSE, pack:true, show : true, size :[100,100])
{
panel
{
RSyntaxTextArea textArea = new RSyntaxTextArea();
textArea.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_JAVA);
}
}
And when i try to run this script as follows:
groovyc -classpath rsyntaxtextarea.jar TextEditorDemo.groovy
I get the errors stating that:
groovy: 9: unable to resolve class RSyntaxTextArea
# line 9, column 19.
RSyntaxTextArea textArea = new RSyntaxTextArea();
^
/home/anto/Groovy/Rsyntax/ST.groovy: 9: unable to resolve class RSyntaxTextArea
# line 9, column 30.
RSyntaxTextArea textArea = new RSyntaxTextArea();
^
/home/anto/Groovy/Rsyntax/ST.groovy: 10: unable to resolve class RSyntaxTextArea
# line 10, column 7.
textArea.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_JAVA);
I guess i have made wrong in running the program. How i do i run the program in this case by defining the classpath too.
It doesn't look like you're importing the package for RSyntaxTextArea. Have you tried adding the following imports to your program?
import org.fife.ui.rtextarea.*;
import org.fife.ui.rsyntaxtextarea.*;
This code should do what you want... You needed to add the RSyntaxTextArea into the view (using the widget method)
You also needed to add it into a JScrollPane, so that it scrolls nicely when full.
import groovy.swing.SwingBuilder
import java.awt.BorderLayout as BL
import static javax.swing.JFrame.EXIT_ON_CLOSE
import org.fife.ui.rsyntaxtextarea.*
RSyntaxTextArea textArea = new RSyntaxTextArea()
textArea.syntaxEditingStyle = SyntaxConstants.SYNTAX_STYLE_JAVA
swing = new SwingBuilder()
frame = swing.frame(title:"test", defaultCloseOperation:EXIT_ON_CLOSE, size:[600,400], show:true ) {
borderLayout()
panel( constraints:BL.CENTER ) {
borderLayout()
scrollPane( constraints:BL.CENTER ) {
widget textArea
}
}
}
edit
Without using widget, your code would need to look something like this:
import groovy.swing.SwingBuilder
import java.awt.BorderLayout as BL
import static javax.swing.JFrame.EXIT_ON_CLOSE
import org.fife.ui.rsyntaxtextarea.*
RSyntaxTextArea textArea = new RSyntaxTextArea()
textArea.syntaxEditingStyle = SyntaxConstants.SYNTAX_STYLE_JAVA
swing = new SwingBuilder()
frame = swing.frame(title:"test", defaultCloseOperation:EXIT_ON_CLOSE, size:[600,400], show:true ) {
borderLayout()
panel( constraints:BL.CENTER ) {
borderLayout()
sp = scrollPane( constraints:BL.CENTER )
sp.viewport.add textArea
}
}
Is there some kind of built-in method or a simple function that will convert Duration into a string in the hh:mm:ss format? For example, I am looking for something that would convert a Duration of 123402 ms into a String of "2:03".
Alternatively, you can use the flags from java.util.Formatter.
action: function() {
txt = "{%tM dur}.{%tS dur}"
}
This will result in a leading 0, as in "02.03", for dur = "123402ms".
You can convert a Duration to a String using String.valueOf(dur). You can then use the Java formatting classes to reformat the String. You have to chop the end of String because of the way JavaFX formats durations as strings (eg '123402.0ms'). If JavaFX had a Long.valueOf(dur) function then this would be easier.
See sample below:
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.text.Text;
import javafx.scene.text.Font;
import javafx.scene.control.Button;
import java.text.SimpleDateFormat;
import java.util.Date;
var fmt = new SimpleDateFormat("m:ss");
var dur: Duration = 123402ms;
var txt: String = String.valueOf(dur);
Stage {
title : "Duration Switch"
scene: Scene {
width: 400
height: 200
content: [
Text {
font : Font {
size: 24
}
x: 10, y: 30
content: bind "Duration={txt}"
},
Button {
translateY: 140
text: "Switch"
action: function() {
var durStr = String.valueOf(dur);
durStr = durStr.substring(0, durStr.indexOf("."));
var date = new Date(Long.parseLong(durStr));
txt = fmt.format(date);
}
}
]
}
}