MouseMoveEvent can not pass into my subclass (Python, Qt) - callback

I put a subclass (QDicomLabel_contrast) inherited from QLabel in a QWidget, and the mouse move event in QDicomLabel_contrast can not be call back. The code is:
from PyQt5.QtWidgets import *
import sys
class QDicomLabel_contrast(QLabel):
def __init__(self,parent=None):
super(QDicomLabel_contrast,self).__init__(parent)
self.setStyleSheet("background-color:black")
self.setMouseTracking(True)
def mouseMoveEvent(self, QMouseEvent):
pos = QMouseEvent.pos()
print(pos.x(), pos.y())
if __name__ == '__main__':
class MainWindow(QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.resize(500,500)
self.imagelabel = QDicomLabel_contrast()
self.imagelabel.resize(300,300)
self.imagelabel.setParent(self)
#self.imagelabel.show()
self.imagelabel.setGeometry(10, 20, 300,300)
widget = QWidget()
self.setCentralWidget(widget)
app = QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec_()
the mouseMoveEvent in QDicomLabel_contrast can not be called. However, if I use self.imagelabel.show() instead of self.imagelabel.setParent(self), the mouseMoveEvent can be called, just like:
from PyQt5.QtWidgets import *
import sys
class QDicomLabel_contrast(QLabel):
def __init__(self,parent=None):
super(QDicomLabel_contrast,self).__init__(parent)
self.setStyleSheet("background-color:black")
self.setMouseTracking(True)
def mouseMoveEvent(self, QMouseEvent):
pos = QMouseEvent.pos()
print(pos.x(), pos.y())
if __name__ == '__main__':
class MainWindow(QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.resize(500,500)
self.imagelabel = QDicomLabel_contrast()
self.imagelabel.resize(300,300)
#self.imagelabel.setParent(self)
self.imagelabel.show()
self.imagelabel.setGeometry(10, 20, 300,300)
widget = QWidget()
self.setCentralWidget(widget)
app = QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec_()

I has found the solution.
The reason why mouse move function can not be called is that the mouse move event will be passed to QWidget. So, if I indicate the parent to QWidget, the problem will be ok: self.imagelabel.setParent(widget).

Related

How to display a simple Message in Ultimaker Cura

I have the following code:
from UM.Extension import Extension
from UM.i18n import i18nCatalog
i18n_catalog = i18nCatalog("CostAndTimePlugin")
class CostAndTimePlugin(Extension):
def __init__(self):
super().__init__()
self.name = "Cost And Time"
self.addMenuItem(i18n_catalog.i18n("Sample"), self.message)
def message(self):
pass
and message() should display a simple message
I tried this:
def message(self):
self._message = Message(i18n_catalog.i18nc("#info:status", "Smaple..."),
title=i18n_catalog.i18nc("#title", "Auto-Sample"))
self._message.show()
but it did not work

Get PrepareStament Variable in Scala

I would like to make the prepareStatement serializable
A preparedStatement is not serializable. I have to build a serializable structure that wraps the call and the parameters to control the construction of the said statement during the deserialization
Here are the classes I created to wrap the PrepareStament
import java.sql._
import java.sql.SQLException
import java.util
import java.util.Collections
import avro.shaded.com.google.common.collect.ImmutableMap
import scala.collection.immutable.HashMap
import scala.collection.mutable
class WrappedConnection(var delegate: Connection) extends Serializable {
def prepareStatement(sql: String): WrappedPreparedStatement = {
val ps = delegate.prepareStatement(sql)
new WrappedPreparedStatement(sql, ps)
}
// delegate all Connection methods to the delegate
}
class WrappedPreparedStatement(var sql: String, var delegate: PreparedStatement) extends Serializable {
private var parameters: mutable.Map[Integer, Object] = mutable.Map.empty[Integer, Object]
override def toString: String = sql
def apply( delegateVar: PreparedStatement) {
delegate = delegateVar
parameters = mutable.Map.empty[Integer, Object]
}
def getParameters = parameters
// TODO: many methods to delegate
#throws[SQLException]
def setString(parameterIndex: Int, x: String): Unit = {
delegate.setString(parameterIndex, x)
parameters.put(parameterIndex, x)
}
#throws[SQLException]
def executeQuery = { // perhaps you might want to do some logging here?
delegate.executeQuery
}
// delegate all PreparedStatement methods to the delegate
}
object WrappedConnection {
def apply(delegate: Connection): WrappedConnection = new WrappedConnection(delegate)
}
This is the test code
val connection = MsSqlUtils.createConnectionFactory(config)
val conn = connection()
val wrapperConn = WrappedConnection(conn)
val statement = wrapperConn.prepareStatement("select * from users")
Currently, my problem is to access the variables of my prepareStatement object and create get functions that will return them.
When I talk about variables I talk about the one shown in the picture below not the one in the querie
Anyone know how to access these variables?

glClearColor display ony a black screen

I struggle to understand why the window I'm doing with openGL stays black.
I don't see where I made a mistake in my code :
import com.jogamp.opengl.awt.GLCanvas
import com.jogamp.opengl.{GL, GLAutoDrawable, GLCapabilities, GLEventListener, GLProfile}
import javax.swing.{JFrame, WindowConstants}
class Game extends JFrame ("Just a window OMG.") with GLEventListener {
val profile: GLProfile = GLProfile.get(GLProfile.GL4)
val capabilities = new GLCapabilities(profile)
val canvas = new GLCanvas(capabilities)
this.setName("Just a window OMG.")
this.getContentPane.add(canvas)
this.setSize(800, 600)
this.setLocationRelativeTo(null)
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE)
this.setVisible(true)
this.setResizable(false)
canvas.requestFocusInWindow
def play(): Unit = {
}
override def display(drawable: GLAutoDrawable): Unit = {
val gl = drawable.getGL.getGL4
gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT)
gl.glFlush()
}
override def dispose(drawable: GLAutoDrawable): Unit = {}
override def init(drawable: GLAutoDrawable): Unit = {
val gl = drawable.getGL.getGL4
gl.glClearColor(1f, 0f, 0f, 1.0f)
}
override def reshape(drawable: GLAutoDrawable, x: Int, y: Int, width: Int, height: Int): Unit = {}
}
object Main {
def main(args: Array[String]): Unit = {
val game = new Game()
game.play()
}
}
I also tried to put the glClear inside the display method and also put a glClearColor in the init method.
EDIT:
I found it.
Actually the display and init meth were never called.
The listener wasn't attached to the canvas and then it never received any event.
The problem is that I was missing the line
canvas.addGLEventListener(this)
just after the canvas initialisation.
(this line)
val canvas = new GLCanvas(capabilities)
(I'm answering my own question)
So actually the problem was that the display and init method were never called.
As far as I understood it, the GLEventListener is waiting for event and those would trigger the call of the init and display method.
The "thing" that would notice the GLEventListener is the canvas, yet my canvas and the GLEventListener weren't binded.
To do so I added the line
canvas.addGLEventListener(this)
Just after I initialized the canvas and it then I could notice the init and display method called.

scalajs: calling a javascript function with a js.Dynamic.literal works, but not with a js.Object

I am writing a scalajs facade for a function that expects an object parameter.
Simplifying, it looks like this:
notification.js
function notification(options) {
console.log("options", options);
}
example.scala:
import scala.scalajs.js
class Options(val message: String, val timeout: js.UndefOr[Int] = js.undefined) extends js.Object
#js.native
#js.annotation.JSGlobalScope
object DOMGlobalScope extends js.Object {
def notification(options: js.Object): Unit = js.native
}
DOMGlobalScope.notification(js.Dynamic.literal(message = "hello", timeout = 100))
// the browser prints: options {timeout: 100}
DOMGlobalScope.notification(new Options(message = "hello", timeout = 100))
// the browser prints: options a {timeout: 100} << what is this a?
The library that I am facading, it works if I use js.Dynamic.literal, but it doesn't if I use new Options.
Is this related to that a?
How can I solve this?
And, why can't I use a case class Options?

Scala macro for shortcut

I have defined the following macros to get file, line and object/class from current location:
http://pastebin.com/UsNLemnK
Using SBT, I have defined two projects, in order to compile the macros first, then the actual project using these macros.
The purpose of these macros are to be be used in a log method:
def log( msg: Any, srcFile: String = "", srcLine: String = "", srcClass:String = "")
I am then using this log method as follows:
log(msg, s"$F_",s"$L_",s"$C_")
where F_, L_ and C_ are defined in the macro.
Now, I would like to create a shortcut to avoid this boilerplate and just call:
log(msg)
which should automatically be replaced by
log(msg, s"$F_",s"$L_",s"$C_")
I could define a macro to do this:
def log_(msg: String) : Unit = macro logImpl
def logImpl( c: Context )(msg: c.Expr[String]): c.Expr[Unit] = {
import c.universe._
reify( log(msg.splice, srcFile=s"$F_", srcLine=s"$L_", srcClass=s"$C_") )
}
but again, this macro needs to be compiled before the project, where the log function itself is defined... So I don't see how to solve the compilation dependencies cycle...
Any suggestion about how to do this?
Thanks
Barring the use of macro annotations (which would necessarily and significantly alter your API's syntax), the problem you have to face is that you need the type-checked identifier of your log function.
Since you can't import the entire log implementation, a solution would be to:
wrap the method into a trait,
define this trait in the "macro" project,
add an implicit parameter to the log_ method,
in your "main" project, create an implementation of this trait, and instantiate this implementation in an implicit val visible everywhere you'd like to use the log_ macro (in the package object for example).
Of course, you could also use a simple FunctionN here and avoid the trait definition and implementation, but this way you'll avoid potential conflicts with other same-typed implicits.
In general, your code would resemble the following:
//"macro" project
trait EncapsulatingTrait {
def yourMethod(...)
}
object Macros {
def myMacro(...)(implicit param: EncapsulatingTrait) = macro myMacroImpl
def myMacroImpl( c: Context )(...)
(param: c.Expr[EncapsulatingTrait]): c.Expr[...] = {
import c.universe._
reify(param.splice.yourMethod(...))
}
}
//--------------------------
//"main" project
class Impl extends EncapsulatingTrait {
def yourMethod(...)
}
...
implicit val defaultParam = new Impl
import Macros.myMacro
myMacro(...)
In your specific case, here's how an implementation could look like:
//"macro" project
package yourpackage
import java.io.File
import language.experimental.macros
import scala.reflect.macros.Context
trait LogFunction {
def log( msg: Any, srcFile: String = "", srcLine: Int = -1, srcClass:String = "")
}
object Macros {
// get current line in source code
def L_ : Int = macro lineImpl
def lineImpl( c: Context ): c.Expr[Int] = {
import c.universe._
val line = Literal( Constant( c.enclosingPosition.line ) )
c.Expr[Int]( line )
}
// get current file from source code (relative path)
def F_ : String = macro fileImpl
def fileImpl( c: Context ): c.Expr[String] = {
import c.universe._
val absolute = c.enclosingPosition.source.file.file.toURI
val base = new File( "." ).toURI
val path = Literal( Constant( c.enclosingPosition.source.file.file.getName() ) )
c.Expr[String]( path )
}
// get current class/object (a bit sketchy)
def C_ : String = macro classImpl
def classImpl( c: Context ): c.Expr[String] = {
import c.universe._
val class_ = Literal( Constant( c.enclosingClass.toString.split(" ")( 1 ) ) )
c.Expr[String]( class_ )
}
def log_(msg: String)(implicit logFunc: LogFunction) : Unit = macro logImpl
def logImpl( c: Context )(msg: c.Expr[String])(logFunc: c.Expr[LogFunction]): c.Expr[Unit] = {
import c.universe._
reify( logFunc.splice.log(msg.splice, srcFile=fileImpl(c).splice, srcLine=lineImpl(c).splice, srcClass=classImpl(c).splice) )
}
}
//--------------------------
//"main" project
import yourpackage.LogFunction
class LogImpl extends LogFunction {
def log( msg: Any, srcFile: String = "", srcLine: Int = -1, srcClass:String = "") {
println(List(msg,srcFile,srcLine,srcClass).mkString("|"))
}
}
object testLog {
def main(args: Array[String]): Unit = {
implicit val defaultLog = new LogImpl
import yourpackage.Macros.log_
log_("blah")
}
}
(note that I had to correct the signature of log_ and tweak the macro call a bit)