adding context QMenu to left click on a button in PySide - contextmenu

I want to add context menu to left click of mouse button pressed over emailbtn
from PySide import QtCore,QtGui
import sys
class ToolBarUI(QtGui.QWidget):
def __init__(self,*args,**kwargs):
super(ToolBarUI,self).__init__(*args,**kwargs)
self.createActions()
self.floatingToolBar()
pass
def sizeHint(self):
return QtCore.QSize(65,45)
def buttons(self):
x,y=15,35
self.btnVLay=QtGui.QVBoxLayout(self)
self.setLayout(self.btnVLay)
self.btnVLay.setContentsMargins(0,0,0,0)
self.incSavbtn=QtGui.QPushButton("Save")
self.incSavbtn.setMinimumSize(QtCore.QSize(x,y))
self.emailbtn=QtGui.QPushButton("Email")
self.emailbtn.setMinimumSize(QtCore.QSize(x,y))
self.upldbtn=QtGui.QPushButton("Upload")
self.upldbtn.setMinimumSize(QtCore.QSize(x,y))
self.setPrjbtn=QtGui.QPushButton("Set Project")
self.setPrjbtn.setMinimumSize(QtCore.QSize(x,y))
self.setThumb=QtGui.QPushButton("Set thumb")
self.setThumb.setMinimumSize(QtCore.QSize(x,y))
self.shwMatbtn=QtGui.QPushButton("Show Material")
self.shwMatbtn.setMinimumSize(QtCore.QSize(x,y))
self.fixtexbtn=QtGui.QPushButton("Fix Texture Paths")
self.fixtexbtn.setMinimumSize(QtCore.QSize(x,y))
btns = [self.incSavbtn,self.emailbtn,self.upldbtn,self.setPrjbtn,self.setPrjbtn,self.setThumb,self.shwMatbtn,self.fixtexbtn]
[self.btnVLay.addWidget(each) for each in btns]
def contextMenuEvent(self, event):
menu = QtGui.QMenu(self)
menu.addAction(self.emlSel)
menu.addAction(self.emlScn)
menu.addAction(self.emlBufr)
#menu.exec_(self.emailbtn.mapToGlobal(QtCore.QPoint(0,0)))
#menu.exec_(event.globalPos())
def createActions(self):
self.emlSel = QtGui.QAction("Email Selected", self)
self.emlScn = QtGui.QAction("Email this Scene", self)
self.emlBufr = QtGui.QAction("Email Current Frame Buffer", self)
def floatingToolBar(self):
self.buttons()
self.setLayout(self.btnVLay)
self.show()
pass
if __name__ =='__main__':
app = QtGui.QApplication(sys.argv)
win = ToolBarUI()
win.show()
sys.exit(app.exec_())
I have tried in contextMenuEvent method but that gives me on right click :/
What am i missing ? Any help will be appreciated.

It works in Linux but not in windows.
Below is code I used for systemtrayicon with left click support in windows. This might work for you as well.
QtCore.QObject.connect(self, QtCore.SIGNAL("activated(QSystemTrayIcon::ActivationReason)"), self.iconActivated)
def iconActivated(self, reason):
if reason == QtGui.QSystemTrayIcon.Trigger: // left click, right click is Context
self.contextMenu().activateWindow() // menu will disappear on clicking any where other than menu
self.contextMenu().popup(QtGui.QCursor.pos()) // display menu at cursor location

Looks like you could use the setMenu method:
#!/usr/bin/env python
#-*- coding:utf-8 -*-
from PyQt4 import QtCore, QtGui
class myWindow(QtGui.QWidget):
def __init__(self, parent=None):
super(myWindow, self).__init__(parent)
self.actionHello = QtGui.QAction(self)
self.actionHello.setText("Hello")
self.menu = QtGui.QMenu(self)
self.menu.addAction(self.actionHello)
self.buttonShow = QtGui.QPushButton(self)
self.buttonShow.setText("Button with menu")
self.buttonShow.setMenu(self.menu)
self.layout = QtGui.QVBoxLayout(self)
self.layout.addWidget(self.buttonShow)
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
app.setApplicationName('myWindow')
main = myWindow()
main.show()
sys.exit(app.exec_())

Related

Install Snyk in Jenkins "Global Tool Configuration" using groovy

I'm trying to add a Snyk installation to Jenkins using groovy. The plugin is installed and I can see the installation option in Global Tool Configuration:
The problem is the Descriptor is not available until I manually add the installer and click Save. If I don't do this task manually, which I want to prevent, it causes my code to fail with the following error message "Cannot invoke method setInstallations() on null object"
My code:
import hudson.model.*
import jenkins.model.*
import hudson.tools.*
import hudson.tasks.*
import io.snyk.jenkins.tools.SnykInstaller
import io.snyk.jenkins.tools.SnykInstallation
def snyk_name = "Snyk"
def snyk_home = ""
def snyk_installer = new SnykInstaller("", "latest", 24)
def snyk_properties = new InstallSourceProperty([snyk_installer])
def instance = Jenkins.getInstance()
println("[init.groovy.d] START Configuring Snyk Installation...")
// Get the GlobalConfiguration descriptor of Snyk plugin.
def snyk_conf = instance.getDescriptor("io.snyk.jenkins.SnykStepBuilder.SnykStepBuilderDescriptor")
def snyk_inst = new SnykInstallation(
snyk_name,
snyk_home,
[snyk_properties]
)
// Only add the new Snyk setting if it does not exist - do not overwrite existing config
def snyk_installations = snyk_conf.getInstallations()
def snyk_inst_exists = false
snyk_installations.each {
installation = (SnykInstallation) it
if (snyk_inst.getName() == installation.getName()) {
snyk_inst_exists = true
println("Found existing installation: " + installation.getName())
}
}
if (!snyk_inst_exists) {
snyk_installations += snyk_inst
snyk_conf.setInstallations((SnykInstallation[]) snyk_installations)
snyk_conf.save()
}
// Save the state
instance.save()
println("[init.groovy.d] END")
Is there any way to do what I want programmatically?
After testing your groovy on my local Jenkins (v 2.263.1) I came up with the below which then worked for me:
import hudson.model.*
import jenkins.model.*
import hudson.tools.*
import hudson.tasks.*
import io.snyk.jenkins.tools.*
def instance = Jenkins.getInstance()
def snyk_name = "SnykLatest"
def snyk_home = ""
def snyk_installer = new SnykInstaller("", "latest", 24L, null)
def snyk_properties = new InstallSourceProperty([snyk_installer])
println("[init.groovy.d] START Configuring Snyk Installation...")
// Get the GlobalConfiguration descriptor of Snyk plugin.
def snyk_conf = instance.getDescriptor("io.snyk.jenkins.tools.SnykInstallation")
def snyk_inst = new SnykInstallation(
snyk_name,
snyk_home,
[snyk_properties]
)
// Only add the new Snyk setting if it does not exist - do not overwrite existing config
def snyk_installations = snyk_conf.getInstallations()
def snyk_inst_exists = false
snyk_installations.each {
installation = (SnykInstallation) it
if (snyk_inst.getName() == installation.getName()) {
snyk_inst_exists = true
println("Found existing installation: " + installation.getName())
}
}
if (!snyk_inst_exists) {
snyk_installations += snyk_inst
snyk_conf.setInstallations((SnykInstallation[]) snyk_installations)
snyk_conf.save()
}
// Save the state
instance.save()
println("[init.groovy.d] END")
In basic Terms the SnykInstaller was expecting 4 values not 3. Groovy also took the 3rd value as an Integer when it was expecting a Long Value.
References:
https://javadoc.jenkins.io/plugin/snyk-security-scanner/io/snyk/jenkins/tools/SnykInstaller.html
https://github.com/jenkinsci/snyk-security-scanner-plugin/blob/master/src/main/java/io/snyk/jenkins/tools/SnykInstaller.java
https://github.com/jenkinsci/snyk-security-scanner-plugin/blob/master/src/main/java/io/snyk/jenkins/tools/PlatformItem.java

widgetexceptionerror i am trying to build a simple app using python kivy and this is the error which i am getting

I am trying to build a app using kivy and I am getting a widget expression error
raise WidgetException('Cannot add %r, it already has a parent %r'
kivy.uix.widget.WidgetException: Cannot add <kivy.uix.button.Button object at 0x0000026C4F999E40>, it already has a parent <main.SpartanGrid object at 0x0000026C4F1480B0>
this is my code
import turtle
import kivy
from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
wn = turtle.Screen()
wn.setup(height=1.0,width=1.0)
wn.bgcolor('black')
turtle.hideturtle()
usr = turtle.textinput("what user wish to", "please tell weather you want to access or
write to the file")
usr.lower()
if usr == 'access':
with open("C:\\Users\\Badri\\Documents\\New folder\\pyproject.txt", 'r') as pr:
cont = pr.read()
turtle.color('red')
turtle.write(cont, align='center', font=('caliber', 25, 'normal'))
elif usr == 'write':
class SpartanGrid(GridLayout):
def __init__(self,**kwargs):
super(SpartanGrid,self).__init__()
self.cols=3
self.add_widget(Label(text="person Name:"))
self.s_name=TextInput()
self.add_widget(self.s_name)
self.add_widget(Label(text="person ph.no"))
self.s_no = TextInput()
self.add_widget(self.s_no)
self.press = Button(text="submit")
self.add_widget(self.press)
self.press.bind(on_press=self.submit)
self.add_widget(self.press)
def submit(self,instance):
print("successful")
class SpartanApp(App):
def build(self):
return SpartanGrid()
if __name__ == "__main__":
SpartanApp().run()
else:
turtle.write("the input is not valid",align='center',font=('caliber',25,'normal'))
turtle.bye()
turtle.done()

How to use share button to share content of my app

I'm working with kivymd and using an MDFloatingActionButtonSpeedDial cannot figure out how to use it to share the content of the app with a link to download the like we share youtube video on WhatsApp, just like above
Here's my code
data = {
"facebook": "Facebook",
"whatsapp": "WhatsApp",
"instagram": "Instagram",
"twitter": "Twitter",
}
def callback(self, instance):
print('Hello')
print(instance.icon)
if instance.icon == "facebook":
print('Share it on Facebook')
elif instance.icon == 'whatsapp':
print('Share it on WhatsApp')
elif instance.icon == 'twitter':
print('Share it on Twitter')
else:
print('Share it on Instagram')
# Native method for Android.
def share(title, text):
from kivy import platform
if platform == 'android':
from jnius import autoclass
PythonActivity = autoclass('org.kivy.android.PythonActivity')
Intent = autoclass('android.content.Intent')
String = autoclass('java.lang.String')
intent = Intent()
intent.setAction(Intent.ACTION_SEND)
intent.putExtra(Intent.EXTRA_TEXT, String('{}'.format(text)))
intent.setType('text/plain')
chooser = Intent.createChooser(intent, String(title))
PythonActivity.mActivity.startActivity(chooser)

Is there a way to automatically change epic state to done when all the linked stories and tasks are complete

I am new to JIRA and Kanban. I was expecting that when I create an epic and link some stories and tasks to it. The status of the epic will automatically change (e.g. to done) when all the stories and tasks linked to it are done. But it seems this is not the case. I can move the epic from the Backlog to the Done column even when its linked tasks and stories are still in the backlog. Is there a way to make JIRA prevent that from happening?
I have been working on something similar. My intention was to set assigne of all linked issues of another one to a specific user when the status changes to a specific state.
I did this with a postfunction of the workflow of type: "Set Field Value to constant or Groovy expression"
In your situation I would do the following:
go to "Close" transition, and click configure.
select postfunctions, and add the type i told you.
mark the chekbox that says execute only if condition is true
set your condition. Probably something like issue.epic=your epic.
Then you add your script, where you recover alll the issues linked to the epic, and check their status.
Create your logic so that if everithing is as it should be, you just change the status, using MutableIssue object.
remember that a field is going to be modified by this script, and i guess you cant choose status as field to be set. If this happens, choose summary, and store the current value, and use it to end your script, and set the summary value, whtih the same you had.
Publish your workflow.
Excuse me if it is not clear, but is difficult to explain. Let me know if you need somenthing else.
PD: If you just want to do this at some specific moment and not for every epics automatically, just add Script Runner plugin, and run your script in the console. Much easier.
Regards
Maybe it helps you:
I used jira with system language set to "Russian" (and i'm not good in groovy), that's why script below contains language dependencies (you should edit code if you use differ from my jira system language! At least change )
Use Scrip Runner plugin
Create "Custom listener" and paste code (code is not so good as can be but it's working):
import com.atlassian.jira.component.ComponentAccessor;
import com.atlassian.jira.issue.IssueManager;
import com.atlassian.jira.issue.Issue;
import com.atlassian.jira.issue.link.IssueLinkManager;
import com.atlassian.jira.issue.link.IssueLink;
import com.atlassian.jira.issue.ModifiedValue;
import com.atlassian.jira.issue.util.DefaultIssueChangeHolder;
import com.atlassian.jira.issue.customfields.option.Options;
import com.atlassian.jira.issue.customfields.option.Option;
import com.atlassian.jira.issue.fields.config.FieldConfig;
import com.atlassian.jira.issue.customfields.manager.OptionsManager;
import com.atlassian.jira.ComponentManager;
ComponentManager componentManager = ComponentManager.getInstance();
def groupMan = ComponentAccessor.getGroupManager()
def authCon = ComponentAccessor.getJiraAuthenticationContext()
def customFieldManager = ComponentAccessor.getCustomFieldManager()
def changeHolder = new DefaultIssueChangeHolder();
IssueManager issueManager = ComponentAccessor.getIssueManager();
OptionsManager optionsManager = componentManager.getComponentInstanceOfType(OptionsManager.class);
IssueLinkManager issueLinkManager = ComponentAccessor.getIssueLinkManager()
def curUser = authCon.getUser()
def issue = event.issue
def epicLinkCf = customFieldManager.getCustomFieldObjects(issue).find {it.name == 'Epic Link'}
if(!epicLinkCf) {log.warn "No Epic Link field"; return}
log.warn "Existing Epic Link: ${epicLinkCf.getValue(issue)}"
String epicIssue = epicLinkCf.getValue(issue)
Issue epic = issueManager.getIssueObject(epicIssue) // epicKey is passed into your script
// Check if Epic link is exist
if(!epic)
return true
def newEpicState = "Сделано"
log.warn "Epic: " + epic
List<IssueLink> allOutIssueLink = issueLinkManager.getOutwardLinks(epic.getId());
for (Iterator<IssueLink> outIterator = allOutIssueLink.iterator(); outIterator.hasNext();) {
IssueLink issueLink = (IssueLink) outIterator.next();
log.warn "child link type: " + issueLink.getIssueLinkType().getName()
// Check status of all issues from epic
if (issueLink.getIssueLinkType().getName() == "Epic-Story Link") {
Issue chIssue = issueLink.getDestinationObject();
log.warn "child state: " + chIssue.getStatusObject().getName()
if(chIssue.getStatusObject().getName() == "В процессе") {
newEpicState = "В процессе"
} else if (chIssue.getStatusObject().getName() != "Закрыто" && newEpicState != "В процессе") {
newEpicState = "Сделать"
}
}
}
def epicStatusCf = customFieldManager.getCustomFieldObjects(epic).find {it.name == 'Epic Status'}
log.warn "Current epic status: " + epicStatusCf.getValue(epic)
FieldConfig epicStatusFieldConfig = epicStatusCf.getRelevantConfig(epic);
String oldStatus = epicStatusCf.getValue(epic)
log.warn "New epic status: " + newEpicState
// Set new status if it necessary
if (oldStatus != newEpicState) {
Options epicStatusOptions = optionsManager.getOptions(epicStatusFieldConfig);
Option epicStatusDoneOption = epicStatusOptions.getOptionForValue(newEpicState, null);
epicStatusCf.updateValue(null, epic, new ModifiedValue(epic.getCustomFieldValue(epicStatusCf),epicStatusDoneOption),changeHolder)
log.warn "Epic status is updated!"
}
If you're using Scriptrunner then you should be good to use the scriptrunner code. Please check this code from scriptrunner:
// Add the next line as a condition to the script listener, so it gets executed only for epic issues, the line must be written uncommented:
// issue.isEpic
// Check if the resolution has been changed
def resolutionChange = changelog.items.find {
(it as Map).field == 'resolution'
} as Map
logger.info("The resolution change of issue '${issue.key}': ${resolutionChange}.")
if (!resolutionChange) {
logger.info("The resolution didn't change.")
return
}
// Compute the 'Epic Status' value to set based on the resolution value
def newEpicStatusValue = (resolutionChange.toString == 'Done') ? 'Done' : 'To Do'
// Get the 'Epic Status' field ID
final epicStatusField = get("/rest/api/2/field")
.asObject(List)
.body
.find {
(it as Map).name == 'Epic Status'
} as Map
def epicStatusFieldId = epicStatusField.id
logger.info("Updating Epic Status field (${epicStatusFieldId}) to '${newEpicStatusValue}'.")
// Update the 'Epic Status' field value
put("/rest/api/2/issue/${issue.key}")
.queryString("overrideScreenSecurity", Boolean.TRUE)
.header("Content-Type", "application/json")
.body([
fields: [
(epicStatusFieldId): [value: newEpicStatusValue]
]
])
.asString()
You can automate this code your post-function or automation in jira. Please find the further details in this link.

Update JIRA subtask Fix Version when parent issue Fix Version updated

When an issue is created, the Fix Version field is set to a particular value (say 2.0). Then subtasks are created, and they inherit this value. So far so good. But if later, the issue's Fix Version value is modified (to say 1.0), the subtasks still keep the 2.0 fix version value.
Is there a plugin or technique I can use to keep these fields in sync?
Note: This has been requested as a JIRA feature, but Atlassian doesn't seem to want to do it.
https://jira.atlassian.com/browse/JRA-9016
I know its rather an old question. But here is my code I recently deployed. This is an event listener for issueUpdated event deployed on Script Listener from ScriptRunner plugin. A lot of the code is from Jamie Echlin's examples. It still needs to be tweaked for when a Fix Version field on the Parent is made "empty", it's sub tasks also need to be empty.
package com.custom.listeners
import org.apache.log4j.Category
import com.atlassian.jira.ComponentManager
import com.atlassian.jira.event.issue.AbstractIssueEventListener
import com.atlassian.jira.event.issue.IssueEvent
import com.atlassian.jira.issue.Issue
import com.atlassian.jira.project.version.Version
import com.opensymphony.workflow.InvalidInputException
import com.atlassian.jira.config.SubTaskManager
import com.atlassian.jira.issue.IssueManager
import com.atlassian.jira.event.type.EventDispatchOption
import java.util.ArrayList
import java.util.Collection
class FixVersionPBI_To_SBI_1 extends AbstractIssueEventListener
{
Category log = Category.getInstance(FixVersionPBI_To_SBI_1.class)
#Override
void issueUpdated(IssueEvent event)
{
try
{
Issue fix_Issue = event.getIssue()
if (fix_Issue.issueTypeObject.name == "Parent issue type" )
{
List changeItems = event.getChangeLog().getRelated("ChildChangeItem")
if( fix_Issue.fixVersions?.name && changeItems.any {it.get('field')=='Fix Version'} )
{
Collection<Version> fixVersions = new ArrayList<Version>();
fixVersions = fix_Issue.getFixVersions()
Collection subTasks = fix_Issue.getSubTasks();
SubTaskManager subTaskManager = ComponentManager.getInstance().getSubTaskManager();
if (subTaskManager.subTasksEnabled && !subTasks.empty)
{
IssueManager issueManager = ComponentManager.getInstance().getIssueManager()
Collection _subTasks = fix_Issue.getSubTaskObjects()
_subTasks.each
{
it.setFixVersions(fixVersions)
issueManager.updateIssue(event.getUser(), it, EventDispatchOption.ISSUE_UPDATED, false)
}
}
}
}
}
catch (ex)
{
log.debug "Event: ${event.getEventTypeId()} fired for ${event.issue} and caught by FixVersionPBI_To_SBI_1"
log.debug (ex.getMessage())
}
}
}
For Jira 6.4
Your subtasks fixversion fields will be update automatically.
Install ScriptRunner plugin.
OPEN your-jira.host/secure/admin/ViewCustomFields.jspa
ADD the new custom field with (Advanced>Scripted field)
OPEN /plugins/servlet/scriptrunner/builtin?section=script_fields and find new field there.
ADD this script, test it and save.
import com.atlassian.jira.component.ComponentAccessor;
import com.atlassian.jira.config.SubTaskManager;
import com.atlassian.jira.issue.IssueManager;
import com.atlassian.jira.event.type.EventDispatchOption;
def result = "";
def subTasks = issue.getSubTaskObjects()
Collection fixVersions = issue.getFixVersions();
if (!fixVersions.empty) {
SubTaskManager subTaskManager = ComponentAccessor.getSubTaskManager();
if(subTaskManager.subTasksEnabled && !subTasks.empty) {
def user = ComponentAccessor.getJiraAuthenticationContext().getLoggedInUser();
subTasks.each {
if (it.statusObject.name != "Closed") {
it.setFixVersions(fixVersions);
IssueManager issueManager = ComponentAccessor.getIssueManager()
result += it.getKey() + " ";
issueManager.updateIssue(user, it, EventDispatchOption.ISSUE_UPDATED, false);
}
}
if (count > 0) {
result += " versions updated";
}
}
}
return result;
To do it manually, you could do query such as "parent=TEST-123" and then a bulk edit. To do it automatically you would need to have a custom listener (e.g. Script Runner) to detect the Issue Updated event and only do something if the change was an issue update. Updating the subtask Fix Versions will also require that the subtasks are reindexed or your searches will not work as expected.
I don't know of a plugin to do this.

Resources