Pyside global menu not works - pyside

Why not work global menu in PySide? I'm developing a Qt app in Ubuntu 14.04 LTS and the global menu doesn't work with PySide binding. With PyQt4 it works fine with no problem.
Is it a bug?
With Pyside
from PySide import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(400, 300)
self.centralWidget = QtGui.QWidget(MainWindow)
self.centralWidget.setObjectName(_fromUtf8("centralWidget"))
MainWindow.setCentralWidget(self.centralWidget)
self.menuBar = QtGui.QMenuBar(MainWindow)
self.menuBar.setGeometry(QtCore.QRect(0, 0, 400, 25))
self.menuBar.setObjectName(_fromUtf8("menuBar"))
self.menuMenu = QtGui.QMenu(self.menuBar)
self.menuMenu.setObjectName(_fromUtf8("menuMenu"))
MainWindow.setMenuBar(self.menuBar)
self.mainToolBar = QtGui.QToolBar(MainWindow)
self.mainToolBar.setObjectName(_fromUtf8("mainToolBar"))
MainWindow.addToolBar(QtCore.Qt.TopToolBarArea, self.mainToolBar)
self.statusBar = QtGui.QStatusBar(MainWindow)
self.statusBar.setObjectName(_fromUtf8("statusBar"))
MainWindow.setStatusBar(self.statusBar)
self.actionAsd = QtGui.QAction(MainWindow)
self.actionAsd.setObjectName(_fromUtf8("actionAsd"))
self.actionAsd2 = QtGui.QAction(MainWindow)
self.actionAsd2.setObjectName(_fromUtf8("actionAsd2"))
self.menuMenu.addAction(self.actionAsd)
self.menuMenu.addAction(self.actionAsd2)
self.menuBar.addAction(self.menuMenu.menuAction())
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
self.menuMenu.setTitle(_translate("MainWindow", "Menu", None))
self.actionAsd.setText(_translate("MainWindow", "Asd", None))
self.actionAsd2.setText(_translate("MainWindow", "Asd2", None))
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
MainWindow = QtGui.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
With PyQt4
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(400, 300)
self.centralWidget = QtGui.QWidget(MainWindow)
self.centralWidget.setObjectName(_fromUtf8("centralWidget"))
MainWindow.setCentralWidget(self.centralWidget)
self.menuBar = QtGui.QMenuBar(MainWindow)
self.menuBar.setGeometry(QtCore.QRect(0, 0, 400, 25))
self.menuBar.setObjectName(_fromUtf8("menuBar"))
self.menuMenu = QtGui.QMenu(self.menuBar)
self.menuMenu.setObjectName(_fromUtf8("menuMenu"))
MainWindow.setMenuBar(self.menuBar)
self.mainToolBar = QtGui.QToolBar(MainWindow)
self.mainToolBar.setObjectName(_fromUtf8("mainToolBar"))
MainWindow.addToolBar(QtCore.Qt.TopToolBarArea, self.mainToolBar)
self.statusBar = QtGui.QStatusBar(MainWindow)
self.statusBar.setObjectName(_fromUtf8("statusBar"))
MainWindow.setStatusBar(self.statusBar)
self.actionAsd = QtGui.QAction(MainWindow)
self.actionAsd.setObjectName(_fromUtf8("actionAsd"))
self.actionAsd2 = QtGui.QAction(MainWindow)
self.actionAsd2.setObjectName(_fromUtf8("actionAsd2"))
self.menuMenu.addAction(self.actionAsd)
self.menuMenu.addAction(self.actionAsd2)
self.menuBar.addAction(self.menuMenu.menuAction())
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
self.menuMenu.setTitle(_translate("MainWindow", "Menu", None))
self.actionAsd.setText(_translate("MainWindow", "Asd", None))
self.actionAsd2.setText(_translate("MainWindow", "Asd2", None))
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
MainWindow = QtGui.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
Thanks!

Related

how can I solve this error "Exception has occurred: TypeError module() takes at most 2 arguments (3 given)"

class Anime(commands.cog):
def __init__(self, bot):
self.bot = bot
#commands.command()
async def anime(ctx, self, *, query):
try:
anime = animec.anime(query)
except:
await ctx.send(embed=discord.Embed(description="Anime not found", color=discord.Color.blue()))
return
embed = discord.Embed(title=anime.title_english, url=anime.url, description=f"{anime.description[:200]}...",
color=discord.Color.red())
embed.add_field(name="Episodes", value=str(anime.episodes))
embed.add_field(name="Rating", value=str(anime.rating))
embed.add_field(name="Genre", value=str(anime.genres))
embed.add_field(name="Broadcast", value=str(anime.broadcast))
embed.ser_thumbmail(url=anime.poster)
await ctx.send(embed=embed)

grpc error ...No handlers could be found for logger "grpc._common"

I am just getting a hang of grpc and tried to build a custom client-server procedure where the client sends an id and a name corresponding to the id.
Here is the custom.proto file:
syntax = "proto3" ;
// Interface exported by the server
service Detail {
rpc GetName(idx) returns (namex) {}
}
message idx {
int32 id = 1;
}
message namex{
int32 id = 1;
string name = 2;
}
From this proto file custom_pb2 and custom_pb2_grpc.py are generated.
This is the custom_db.json
[{"id": 0, "name":"kiran"},
{"id":1, "name":"kirthana"},
{"id":2, "name":"kishore"}
]
This is custom_resources.py
import json
import custom_pb2
def read_custom_database():
''' Reads the custom database I created.'''
names_list = []
with open("custom_db.json") as custom_db_file:
for item in json.load(custom_db_file):
itemx = custom_pb2.namex(id=item["id"], name=item["name"])
names_list.append(itemx)
return names_list
This is the custom_server.py
import custom_pb2_grpc
import custom_resources
import time
_ONE_DAT_IN_SECONDS = 60*60*24
def get_name(custom_db,idx):
'''Returns name of a given id or none'''
for namex in custom_db:
if namex.id == idx:
return namex.name
return None
class DetailServicer(custom_pb2_grpc.DetailServicer):
"""Provides methods that implements the custom server."""
def __init__(self):
self.db = custom_resources.read_custom_database()
def GetName(self, request, context):
name = get_name(self.db, request)
if name is None:
return "Not Found"
else:
return name
def serve():
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
custom_pb2_grpc.add_DetailServicer_to_server(DetailServicer(), server)
server.add_insecure_port('[::]:12345')
server.start()
try:
while True:
time.sleep(_ONE_DAT_IN_SECONDS)
except KeyboardInterrupt:
server.stop(0)
if __name__ == '__main__':
serve()
This is the custom_client.py
from __future__ import print_function
import random
import grpc
import custom_pb2
import custom_pb2_grpc
import custom_resources
def custom_get_one_name(stub, idx):
name = stub.GetName(idx)
print("Feater called with id %d returned: %s" %(idx,name))
return
def custom_get_names(stub):
custom_get_one_name(stub,2)
custom_get_one_name(stub,1)
def run():
with grpc.insecure_channel('localhost:12345') as channel:
stub = custom_pb2_grpc.DetailStub(channel)
custom_get_names(stub)
if __name__ == '__main__':
run()
The exact error message I get is:
No handlers could be found for logger "grpc._common"
Traceback (most recent call last):
File "custom_client.py", line 30, in <module>
run()
File "custom_client.py", line 27, in run
custom_get_names(stub)
File "custom_client.py", line 19, in custom_get_names
custom_get_one_name(stub,2)
File "custom_client.py", line 13, in custom_get_one_name
name = stub.GetName(idx)
File "/usr/local/lib/python2.7/dist-packages/grpc/_channel.py", line 513, in __call__
state, call, = self._blocking(request, timeout, metadata, credentials)
File "/usr/local/lib/python2.7/dist-packages/grpc/_channel.py", line 500, in _blocking
raise rendezvous
grpc._channel._Rendezvous: <_Rendezvous of RPC that terminated with:
status = StatusCode.INTERNAL
details = "Exception serializing request!"
debug_error_string = "None"
Thanks for the help.
You are trying to pass an integer as the request custom_get_one_name(stub,2) where a Protocol Buffers message of type idx is expected. You should create an idx message and pass that instead like:
custom_get_one_name(stub, custom_pb2_grpc.idx(id=2))

collision between two sprites not working

I Cannot seem to get the 2 sprites to make contact with one another, as when the app runs one of the sprites does not make contact but just goes pass it. I'm not sure whats wrong. Could someone please help me.
import SpriteKit
import GameplayKit
enum BodyType:UInt32{
case caveMan = 1
case Zombie = 2
}
class GameScene: SKScene, SKPhysicsContactDelegate {
var caveMan:SKSpriteNode = SKSpriteNode ()
let swipeRightRec = UISwipeGestureRecognizer ()
var Zombie:SKSpriteNode = SKSpriteNode ()
override func didMove(to view: SKView) {
self.physicsWorld.contactDelegate = self
swipeRightRec.addTarget(self, action: #selector (GameScene.swipedRight ))
swipeRightRec.direction = .right
self.view!.addGestureRecognizer(swipeRightRec)
if let somePlayer:SKSpriteNode = self.childNode(withName: "caveMan") as? SKSpriteNode {
caveMan = somePlayer
caveMan.physicsBody?.affectedByGravity = true
caveMan.physicsBody?.isDynamic = false
caveMan.physicsBody?.categoryBitMask = BodyType.caveMan.rawValue
caveMan.physicsBody?.collisionBitMask = BodyType.Zombie.rawValue
caveMan.physicsBody?.contactTestBitMask = BodyType.Zombie.rawValue
}
if let somePlayer:SKSpriteNode = self.childNode(withName: "Zombie") as? SKSpriteNode {
Zombie = somePlayer
Zombie.physicsBody?.affectedByGravity = false
Zombie.physicsBody?.isDynamic = false
Zombie.physicsBody?.categoryBitMask = BodyType.Zombie.rawValue
Zombie.physicsBody?.collisionBitMask = BodyType.caveMan.rawValue
Zombie.physicsBody?.contactTestBitMask = BodyType.caveMan.rawValue
}
}
#objc func swipedRight() {
print("went right")
moveDown()
}
func moveDown() {
let walkAnimation:SKAction = SKAction(named: "Running")!
let walk:SKAction = SKAction.moveBy(x: 90, y: 0, duration: 1)
let group:SKAction = SKAction.group([walkAnimation, walk])
caveMan.run(group)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches {
self.touchDown(atPoint: t.location(in: self))
break
}
}
func didBegin(_ contact: SKPhysicsContact) {
if (contact.bodyA.categoryBitMask == BodyType.caveMan.rawValue && contact.bodyB.categoryBitMask == BodyType.Zombie.rawValue) {
print ("touched a Zombie")
} else if (contact.bodyB.categoryBitMask == BodyType.caveMan.rawValue && contact.bodyA.categoryBitMask == BodyType.Zombie.rawValue) {
print ("touched a Zombie")
}
}
}
See this: caveMan.physicsBody? That means if a body exists then allow a value to be set. It is called optional binding, or short circuiting in other languages.
You need to create the physics body, it is not given to you for free.
As of right now this is what your code looks like:
caveMan = somePlayer
nil.affectedByGravity = true
nil.isDynamic = false
nil.categoryBitMask = BodyType.caveMan.rawValue
nil.collisionBitMask = BodyType.Zombie.rawValue
nil.contactTestBitMask = BodyType.Zombie.rawValue
what you want to do is:
caveMan = somePlayer
caveMan.physicsBody = SKPhysicsBody(rectangleOf: caveMan.size)
caveMan.physicsBody!.affectedByGravity = true
caveMan.physicsBody!.isDynamic = false
caveMan.physicsBody!.categoryBitMask = BodyType.caveMan.rawValue
caveMan.physicsBody!.collisionBitMask = BodyType.Zombie.rawValue
caveMan.physicsBody!.contactTestBitMask = BodyType.Zombie.rawValue

How to show image in PyQT GUI?

I want to show an Image in GUI using filepicker in PyQT. So far I managed to open image files, but completely confused on how to show image in GUI.
import sys
from PyQt4 import QtGui, QtCore
class Window(QtGui.QMainWindow):
def __init__(self):
super(Window, self).__init__()
self.setGeometry(100, 100, 500, 300)
self.setWindowTitle("PyQT Show Image")
openFile = QtGui.QAction("&File", self)
openFile.setShortcut("Ctrl+O")
openFile.setStatusTip("Open File")
openFile.triggered.connect(self.file_open)
self.statusBar()
mainMenu = self.menuBar()
fileMenu = mainMenu.addMenu('&File')
fileMenu.addAction(openFile)
self.home()
def home(self):
self.show()
def file_open(self):
name = QtGui.QFileDialog.getOpenFileName(self, 'Open File')
file = open(name, 'r')
def run():
app = QtGui.QApplication(sys.argv)
GUI = Window()
sys.exit(app.exec_())
run()
Kindly guide me here on how to show image in GUI. Thank you
How about this?
import sys
from PyQt4 import QtGui, QtCore
class Window(QtGui.QMainWindow):
def __init__(self):
super(Window, self).__init__()
self.setGeometry(100, 100, 500, 300)
self.setWindowTitle("PyQT Show Image")
openFile = QtGui.QAction("&File", self)
openFile.setShortcut("Ctrl+O")
openFile.setStatusTip("Open File")
openFile.triggered.connect(self.file_open)
self.statusBar()
mainMenu = self.menuBar()
fileMenu = mainMenu.addMenu('&File')
fileMenu.addAction(openFile)
self.lbl = QtGui.QLabel(self)
self.setCentralWidget(self.lbl)
self.home()
def home(self):
self.show()
def file_open(self):
name = QtGui.QFileDialog.getOpenFileName(self, 'Open File')
pixmap = QtGui.QPixmap(name)
self.lbl.setPixmap(pixmap.scaled(self.lbl.size()))
def run():
app = QtGui.QApplication(sys.argv)
GUI = Window()
sys.exit(app.exec_())
run()
I have updated the code in accordance with pyQt5 as it can be helpful for some persons.(reference : Controlix's code posted above)
import sys
from PyQt5 import QtGui, QtCore
from PyQt5.QtWidgets import QFileDialog,QLabel,QAction,QMainWindow,QApplication
class Window(QMainWindow):
def __init__(self):
super(Window, self).__init__()
self.setGeometry(100, 100, 500, 300)
self.setWindowTitle("PyQT Show Image")
openFile = QAction("&File", self)
openFile.setShortcut("Ctrl+O")
openFile.setStatusTip("Open File")
openFile.triggered.connect(self.file_open)
self.statusBar()
mainMenu = self.menuBar()
fileMenu = mainMenu.addMenu('&File')
fileMenu.addAction(openFile)
self.lbl = QLabel(self)
self.setCentralWidget(self.lbl)
self.home()
def home(self):
self.show()
def file_open(self):
name = QFileDialog.getOpenFileName(self, 'Open File')
print(name)
pixmap = QtGui.QPixmap(name[0])
self.lbl.setPixmap(pixmap.scaled(self.lbl.size()))
def run():
app = QApplication(sys.argv)
GUI = Window()
sys.exit(app.exec_())
run()

swift 2.0 equivalent for NSOpenPanel

i found this swift 1.2 tutorial to open up a panel. but it doesn't work in swift 2.0.
#IBAction func selectFile(sender: AnyObject) {
var openPanel = NSOpenPanel()
openPanel.title = "Select file"
openPanel.beginWithCompletionHandler({(result:Int) in
if (result = NSFILEHandlingPanelOKButton){
print(openPanel.URL!)
}
})
}
I am getting the error unresolved identifier NSOpenPanel, what would be the swift 2.0 equivalent?
I also tried creating Cocoa class under iOS and MacOS without any luck.
If you haven't, try importing AppKit:
import AppKit
You can read the Apple Docs on it.
as a bonus a custom view with popover..
func chooseDestFolder()->URL?{
//it's an OPEN... :)
let dialog = NSOpenPanel()
//dialog.title = "Choose destination folder"
dialog.message = "Choose destination folder"
dialog.showsResizeIndicator = true
dialog.showsHiddenFiles = false
dialog.canChooseDirectories = true
dialog.canChooseFiles = false
dialog.canCreateDirectories = true
dialog.allowsMultipleSelection = false
dialog.allowedFileTypes = [];
let sv = NSView(frame: NSRect(x: 0, y: 0, width: 300, height: 40))
let menu = NSPopUpButton(radioButtonWithTitle: "AAA", target: nil, action: nil)
menu.frame = CGRect(x: 0, y: 10, width: 100, height: 36)
menu.addItems(withTitles: ["JPG", "PDF", ])
sv.addSubview(menu)
dialog.accessoryView = sv
dialog.accessoryView?.wantsLayer = true
//dialog.accessoryView?.layer?.backgroundColor = NSColor.red.cgColor
dialog.isAccessoryViewDisclosed = true
if (dialog.runModal() == NSApplication.ModalResponse.OK) {
let destUrl = dialog.url
return destUrl
} else {
// User clicked on "Cancel"
return nil
}
}

Resources