GUI using Pygtk and glade - pygtk

i am trying to build a GUI using pygtk and glade on Windows. I am a noob at python GUI building so please excuse my noobness. I Looked up this tutorial and did exactly as it said. The only difference was that I am on Windows 7 Home Premium x64 .
I put a Label and a button in a window using glade as in the tutorial and then i got a libglade xml file. Then i typed the following code
import sys
import pygtk
import gtk
import gtk.glade
pygtk.require("2.0")
class HellowWorldGTK:
def __init__(self):
#Set the Glade file
self.gladefile = "Hello_World.glade"
self.wTree = gtk.glade.XML(self.gladefile)
#Get the Main Window, and connect the "destroy" event
self.window = self.wTree.get_widget("MainWindow")
if (self.window):
self.window.connect("destroy", gtk.main_quit)
if __name__ == "__main__":
hwg = HellowWorldGTK()
gtk.main()
I put both the files in the same folder and then i run a python interpreter from the command line into the folder.Apparently The program runs but the thing is that i'm unable to get the interface all i get on the command line is that that the Program is running. I dont even get an error or something.Is it due to the fact that i'm on Windows?? I thought that GTK was cross-platform and the same code should run on windows as well as on Linux??
Also here is the .glade file generated by GLADE GUI designer
<?xml version="1.0" encoding="UTF-8"?>
<glade-interface>
<!-- interface-requires gtk+ 2.24 -->
<!-- interface-naming-policy project-wide -->
<widget class="GtkWindow" id="Hello world!">
<property name="can_focus">False</property>
<property name="resizable">False</property>
<child>
<widget class="GtkVBox" id="vbox1">
<property name="visible">True</property>
<property name="can_focus">False</property>
<child>
<widget class="GtkLabel" id="Click Here!">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="label" translatable="yes">label</property>
</widget>
<packing>
<property name="expand">True</property>
<property name="fill">True</property>
<property name="position">0</property>
</packing>
</child>
<child>
<widget class="GtkButton" id="Please Click on the Button!">
<property name="label" translatable="yes">button</property>
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="receives_default">True</property>
<property name="use_action_appearance">False</property>
</widget>
<packing>
<property name="expand">True</property>
<property name="fill">True</property>
<property name="position">1</property>
</packing>
</child>
</widget>
</child>
</widget>
</glade-interface>

self.window.show()
At the end of __init__ should do it I think.
EDIT AFTER COMMENT...
self.window = self.wTree.get_widget("MainWindow")
but there is no window called "MainWindow", I think you've called your window "Hello world!", try loading that instead (or renaming your window in glade).
It may be a good idea to check that your window is actially found in the glade file as well.
window_name="Hello World!"
self.window = self.wTree.get_widget(window_name)
if (self.window):
self.window.connect("destroy", gtk.main_quit)
else:
raise Exception("I couldn't find the window called "+window_name+"!")

Related

How to auto refresh QSqlTableModel whene added a new data to a database PyQt5

I want the tableview automatically refresh when there is a new data added to the database
this is my py file
from PyQt5 import *
from PyQt5 import QtSql, QtGui
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import Qt
from PyQt5.QtSql import *
import sys, sqlite3
import psycopg2
import datetime
from datetime import timedelta
from PyQt5.QtCore import QDate
import sys
from PyQt5.uic import loadUiType
ui, _ = loadUiType('test.ui')
class MainApp(QMainWindow, ui):
def __init__(self):
QMainWindow.__init__(self)
self.setupUi(self)
self.Handel_Buttons()
def Handel_Buttons(self):
self.pushButton_2.clicked.connect(self.Handel_Day_Operations_1)
def Handel_Day_Operations_1(self):
connection = psycopg2.connect(user="postgres",
password="password",
host="localhost",
database="database")
self.cur = connection.cursor()
patient_name = self.lineEdit.text()
medecin_name =self.comboBox.currentText()
date_f = datetime.date.today()
time_f = datetime.datetime.now().time()
self.cur.execute(''' INSERT INTO transactions(patient, medecin, date_d, time_d, montant, C_acte, acte, users_id )
VALUES (%s ,%s, %s, %s,)
''', (patient_name , medecin_name, date_f, time_f,))
connection.commit()
self.lineEdit.setText('')
self.Show_tran_table()
def Show_tran_table(self):
database = QSqlDatabase("QPSQL")
database.setHostName("localhost")
database.setDatabaseName("database")
database.setUserName("postgres")
database.setPassword("password")
database.open()
model_ft = QSqlTableModel(db=database)
model_ft.setTable('transactions')
model_ft.setHeaderData(0, Qt.Horizontal,"id")
model_ft.setHeaderData(1, Qt.Horizontal,"medecin")
model_ft.setHeaderData(2, Qt.Horizontal,"patient")
model_ft.setHeaderData(3, Qt.Horizontal,"date")
model_ft.setHeaderData(4, Qt.Horizontal,"temps")
# model_ft.removeColumns(8,1)
date = str(datetime.date.today())
date_1 = str(datetime.date.today() - timedelta(days = 1))
self.tableView.setModel(model_ft)
self.tableView.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
model_ft.setSort(0, Qt.DescendingOrder)
model_ft.select()
filter_ft = "(date_d, time_d) > ('%s'::date, '16:00:00'::time) AND (date_d, time_d) < ('%s'::date, '16:00:00'::time) " % (date_1, date)
model_ft.setFilter(filter_ft)
if __name__ == '__main__':
app = QApplication(sys.argv)
app.setStyle('Fusion')
#app.setWindowIcon(QtGui.QIcon('sifax.ico'))
window = MainApp()
window.show()
sys.exit(app.exec_())
and this is the ui file
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>MainWindow</class>
<widget class="QMainWindow" name="MainWindow">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>1222</width>
<height>600</height>
</rect>
</property>
<property name="windowTitle">
<string>MainWindow</string>
</property>
<widget class="QWidget" name="centralwidget">
<widget class="QTableView" name="tableView">
<property name="geometry">
<rect>
<x>30</x>
<y>160</y>
<width>1171</width>
<height>331</height>
</rect>
</property>
<property name="font">
<font>
<family>Merienda One</family>
<pointsize>11</pointsize>
</font>
</property>
</widget>
<widget class="QLineEdit" name="lineEdit">
<property name="geometry">
<rect>
<x>220</x>
<y>30</y>
<width>341</width>
<height>41</height>
</rect>
</property>
<property name="font">
<font>
<family>Merienda One</family>
<pointsize>10</pointsize>
</font>
</property>
<property name="placeholderText">
<string>Nom du Patient</string>
</property>
</widget>
<widget class="QLabel" name="label_32">
<property name="geometry">
<rect>
<x>40</x>
<y>40</y>
<width>161</width>
<height>31</height>
</rect>
</property>
<property name="font">
<font>
<family>Merienda One</family>
<pointsize>10</pointsize>
</font>
</property>
<property name="text">
<string>Nom Complet de patient</string>
</property>
</widget>
<widget class="QComboBox" name="comboBox">
<property name="geometry">
<rect>
<x>570</x>
<y>30</y>
<width>351</width>
<height>41</height>
</rect>
</property>
<property name="font">
<font>
<family>Merienda One</family>
<pointsize>10</pointsize>
</font>
</property>
<property name="placeholderText">
<string>Nom du Médecin</string>
</property>
<item>
<property name="text">
<string>0</string>
</property>
</item>
<item>
<property name="text">
<string>1</string>
</property>
</item>
</widget>
<widget class="QPushButton" name="pushButton_2">
<property name="geometry">
<rect>
<x>980</x>
<y>30</y>
<width>81</width>
<height>51</height>
</rect>
</property>
<property name="text">
<string>Ajouter</string>
</property>
</widget>
</widget>
<widget class="QStatusBar" name="statusbar"/>
</widget>
<resources/>
<connections/>
</ui>
I try a simple solution that it refresh the table every specific time using this
timer = QTimer(self)
timer.timeout.connect(self.Show_tran_table)
timer.start(5000)
but I get into another problem when I want to update a value in the table I have to be faster than 5 s or the table will refresh and I can't update any value
this gui work on 2 part the first one is for adding data and the 2nd part is for showing data only (the same thing here, but only the table view), what I want when someone add data to the database using the def Handel_Day_Operations_1 (self):in the 2 nd gui that contain only the table view it will refresh automatically with the new row that has been added

Implementation of Qserver and Qmux

I'm learning about jpos. I got jpos programmer's guide with me and I have gone through that.
It helped me a lot in developing my switch.
I have some questions.
Whether I created my switch Correctly?
What are best practices for these situation:
I have a switch get diffrent messages (two types of channel/packager) from one switch and response back to it (qserver and qmux or only qmux or ...)
I have a switch get diffrent messages from diffrent banks and should reply them or forward messages to another (do I need qserver or just a qmux or need to have more configs on txmanager side)
now Im going to implement first situation In my switch flow is in this way:
Q2 will deploy by xml files:
Server.xml
RequestListener Class
TransactionMangare.xml
Here, in QMUX, what I don't understand is:
Q2 will deploy by xml files
(then I have QMUX.xml,Channeladaptor.xml and Listener Class [I want to know in what order it should come])
TransactionMangare.xml
messages with diffrent channel would come to me through a single port. is it possible?
as Qmux would use key (Bit41 and mti) which needs to specify channel before giving to the right one (otherwise would get 41 wrong or it would not parse it at all)
here are my deploy files:
logger.xml
<?xml version="1.0" encoding="UTF-8"?>
<logger name="Q2Logger" class="org.jpos.q2.qbean.LoggerAdaptor">
<log-listener class="org.jpos.util.SimpleLogListener" />
</logger>
server.xml
<?xml version="1.0" encoding="UTF-8"?>
<server class="org.jpos.q2.iso.QServer" logger="Q2Logger" name="TransactionServer">
<attr name="port" type="java.lang.Integer">88800</attr>
<attr name="maxSessions" type="java.lang.Integer">20</attr>
<attr name="minSessions" type="java.lang.Integer">10</attr>
<!-- packager is customised (I also need another packager for another type of messages) -->
<channel class="org.jpos.iso.channel.ASCIIChannel" name="ASCIIChannel" logger="Q2Logger" packager="com.example.transaction.packager.ISO93APackager" header="ISO51300000">
<property name="timeout" value="70000" /> <!-- 7 minutes -->
<property name="keep-alive" value="true" />
</channel>
<!-- can have realm="incoming-request-listener" -> to automatically put into space ???? -->
<request-listener class="com.example.transaction.listener.ServerRequestListener" logger="Q2Logger" name="isoListener">
<property name="space" value="transient:default" />
<property name="queue" value="CerditCardTXNQueue" />
<property name="spaceTimeout" value="60000" />
</request-listener>
</server>
txnmgr.xml
<?xml version="1.0" encoding="UTF-8"?>
<txnmgr name="CreditCardTransactionManager" logger="Q2Logger" class="org.jpos.transaction.TransactionManager">
<property name="space" value="transient:default" />
<property name="queue" value="TXNQueue" />
<property name="sessions" value="5" />
<property name="debug" value="true" />
<participant class="com.example.transaction.participants.PrepareParticipant" logger="Q2Logger" />
<participant class="com.example.transaction.participants.ValidationParticipant" logger="Q2Logger" />
<participant class="com.example.transaction.participants.ProcessParticipant" logger="Q2Logger" />
<participant class="com.example.transaction.participants.SendResponseParticipant" logger="Q2Logger"/>
</txnmgr>
Thanks,

Spring.Net 2, NHibernate 4 Error "Could not load type from string value 'Spring.Data.NHibernate.LocalSessionFactoryObject, Spring.Data.NHibernate'."

I'm attempting to upgrade a project from Spring.Net 1.3.2, NHibernate 3.2 to Spring.Net 2, NHibernate 4.
I get the error "Could not load type from string value 'Spring.Data.NHibernate.LocalSessionFactoryObject, Spring.Data.NHibernate'." When I try to run.
My log shows:
System.Configuration.ConfigurationErrorsException: Error creating context 'spring.root': Could not load type from string value 'Spring.Data.NHibernate.HibernateTransactionManager, Spring.Data.NHibernate'. ---> Spring.Objects.Factory.ObjectCreationException: Error thrown by a dependency of object 'transactionAdvisor' defined in 'file [C:\Users\...\Project.Web\Config\transaction.aop.xml] line 7' : Initialization of object failed : Cannot resolve type [Spring.Data.NHibernate.HibernateTransactionManager, Spring.Data.NHibernate] for object with name 'transactionManager' defined in file [C:\Users\...\Project.Web\Config\hibernate.cfg.xml] line 45
while resolving 'TransactionInterceptor' to 'transactionInterceptor' defined in 'file [C:\Users\...\Project.Web\Config\transaction.aop.xml] line 12' ---> Spring.Core.CannotLoadObjectTypeException: Cannot resolve type [Spring.Data.NHibernate.HibernateTransactionManager, Spring.Data.NHibernate] for object with name 'transactionManager' defined in file [C:\Users\...\Project.Web\Config\hibernate.cfg.xml] line 45 ---> System.TypeLoadException: Could not load type from string value 'Spring.Data.NHibernate.HibernateTransactionManager, Spring.Data.NHibernate'.
at Spring.Core.TypeResolution.TypeResolver.Resolve(String typeName) in c:\_prj\spring-net\src\Spring\Spring.Core\Core\TypeResolution\TypeResolver.cs:line 81
If I just open a cs file and create a Spring.Data.NHibernate.LocalSessionFactoryObject it looks fine, and the namespace is correct.
I did change the references due to version changes. Here's what I have now:
transaction.aop.xml
<object id="transactionAdvisor" type="Spring.Transaction.Interceptor.TransactionAttributeSourceAdvisor, Spring.Data">
<property name="TransactionInterceptor" ref="transactionInterceptor"/>
</object>
<!-- Transaction Interceptor -->
<object id="transactionInterceptor" type="Spring.Transaction.Interceptor.TransactionInterceptor, Spring.Data">
<property name="TransactionManager" ref="transactionManager"/>
<property name="TransactionAttributeSource" ref="attributeTransactionAttributeSource"/>
</object>
<object id="attributeTransactionAttributeSource" type="Spring.Transaction.Interceptor.AttributesTransactionAttributeSource, Spring.Data">
</object>
hibernate.cfg.xml
<object id="placeholder_db_settings" type="Spring.Objects.Factory.Config.PropertyPlaceholderConfigurer, Spring.Core">
<property name="ConfigSections" value="databaseSettings,appSettings,emailSettings"/>
</object>
<db:provider id="DbProvider" provider="SqlServer-2.0" connectionString="Data Source=${db.datasource};Database=${db.database};User ID=${db.user};Password=${db.password};Connect Timeout=${db.connectTimeout}"/>
<object id="hibernateSessionFactory" type="Spring.Data.NHibernate.LocalSessionFactoryObject, Spring.Data.NHibernate">
<property name="DbProvider" ref="DbProvider"/>
<property name="MappingAssemblies">
<list>
<value>IBB.BusinessNet.Services</value>
</list>
</property>
<property name="HibernateProperties">
<dictionary>
<entry key-ref="connection.provider" value-ref="NHibernate.Connection.DriverConnectionProvider"/>
<entry key-ref="show_sql" value-ref="false"/>
<entry key-ref="dialect" value-ref="NHibernate.Dialect.MsSql2008Dialect"/>
<entry key-ref="connection.driver_class" value-ref="NHibernate.Driver.SqlClientDriver"/>
<entry key-ref="connection.pool_size" value-ref="10"/>
<entry key-ref="query.substitutions" value-ref="true 1, false 0, yes 'Y', no 'N'"/>
<entry key-ref="use_outer_join" value-ref="true"/>
<entry key-ref="command_timeout" value-ref="840" />
<entry key-ref="cache.provider_class" value-ref="NHibernate.Caches.SysCache2.SysCacheProvider,NHibernate.Caches.SysCache2" />
</dictionary>
</property>
<property name="ExposeTransactionAwareSessionFactory" value="true" />
</object>
<object id="transactionManager" type="Spring.Data.NHibernate.HibernateTransactionManager, Spring.Data.NHibernate">
<property name="DbProvider" ref="DbProvider"/>
<property name="SessionFactory" ref="hibernateSessionFactory"/>
</object>
<object id="MyHibernateTemplate" type="Spring.Data.NHibernate.Generic.HibernateTemplate">
<property name="SessionFactory" ref="hibernateSessionFactory" />
<property name="TemplateFlushMode" value="Auto" />
<property name="AllowCreate" value="true" />
<property name="CacheQueries" value="true" />
</object>
<object id="HibernateTemplate" type="Spring.Data.NHibernate.HibernateTemplate">
<property name="SessionFactory" ref="hibernateSessionFactory" />
<property name="TemplateFlushMode" value="Auto" />
<property name="AllowCreate" value="true" />
<property name="CacheQueries" value="true" />
</object>
Of course everything is sanitized and trimmed to reduce space. I did not change the mapping hbm files because I didn't find anything saying I should.
I knocked Spring logging to DEBUG, fixed a few issues there. Changing NHibernate to DEBUG doesn't add any logging because it's not getting that far. Spring loads everything else fine. The hibernate.cfg.xml output DEBUG messages with "Ignoring object class loading failure for object X" all of them saying
"Could not load type from string value".
The first ERROR is "GetObjectInternal: error obtaining object transactionManager".
I've banged my head against the wall for hours trying to figure out why. I know there are folks out there who understand this stuff better than myself and can point me in the right direction, so here's my call for help.
Bah, I keep wanting to use the namespace rather than the assembly name. The 2 lines in hibernate.cfg.xml needed to be the name of the DLL.
<object id="hibernateSessionFactory" type="Spring.Data.NHibernate.LocalSessionFactoryObject, Spring.Data.NHibernate4">
...
<object id="transactionManager" type="Spring.Data.NHibernate.HibernateTransactionManager, Spring.Data.NHibernate4">

Display Hibernate SQL To Console (Spring)

I'm working with spring 3, hibernate 4. I'm trying to follow this tutorial http://www.mkyong.com/hibernate/hibernate-display-generated-sql-to-console-show_sql-format_sql-and-use_sql_comments/, but my hibernate configuration is different:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd">
<!-- JDBC Data Source. It is assumed you have MySQL running on localhost port 3306 with
username root and blank password. Change below if it's not the case -->
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/project"/>
<property name="username" value="root"/>
<property name="password" value="1234"/>
<property name="validationQuery" value="SELECT 1"/>
<property name="show_sql" value="true" />
<property name="format_sql" value="true" />
<property name="use_sql_comments" value="true" />
</bean>
</beans>
And the properties show_sql, format_sql and use_sql_comments are not working this way. I get this exception:
Caused by: org.springframework.beans.NotWritablePropertyException: Invalid property 'show_sql' of bean class [org.apache.commons.dbcp.BasicDataSource]: Bean property 'show_sql' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
Is there anyway to achieve the tutorial with the definition of the bean??
show_sql not a property of org.apache.commons.dbcp.BasicDataSource . You have to define it in session factory configuration.
like this
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="data" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.H2Dialect</prop>
<prop key="hibernate.current_session_context_class">thread</prop>
<prop key="hibernate.transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
The simplest approach probably is to set following logger to DEBUG:
org.hibernate.SQL
If you use log4j, find / create a log4j.properties file on your classpath root and add
log4j.logger.org.hibernate.SQL=DEBUG
See here for more info about log4j properties: http://logging.apache.org/log4j/1.2/manual.html
As I'm using JEE 8 and JBoss EAP, I managed to got the SQL after adding this line:
-Dorg.jboss.as.logging.per-deployment=false
on the end of "VM arguments" (Server tab -> JBoss Properties -> Open lauch configuration).

error when running red5 application on windows

I made very sample application for red5
I set WEB-INF(red5-web.properties, red5-web.xml, web.xml)
when I runnig the red.bat I view in the debug this error code :
[INFO] [Launcher:/test] org.springframework.beans.factory.xml.XmlBeanDefi
nitionReader - Loading XML bean definitions from ServletContext resource [/WEB-I
NF/red5-web.xml]
Exception in thread "Launcher:/test" org.springframework.beans.factory.xm
l.XmlBeanDefinitionStoreException: Line 25 in XML document from ServletContext r
esource [/WEB-INF/red5-web.xml] is invalid; nested exception is org.xml.sax.SAXP
arseException; lineNumber: 25; columnNumber: 68; cvc-id.2: There are multiple oc
currences of ID value 'web.handler'
and my client can't connect to server :(
from your description its impossible to say exactly what you've done.
You might better start to use for example the existing demo application that ship with every release.
Sebastian
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:lang="http://www.springframework.org/schema/lang"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.0.xsd">
<bean id="placeholderConfig" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="/WEB-INF/red5-web.properties" />
</bean>
<bean id="web.context" class="org.red5.server.Context"
autowire="byType" />
<bean id="web.scope" class="org.red5.server.WebScope"
init-method="register">
<property name="server" ref="red5.server" />
<property name="parent" ref="global.scope" />
<property name="context" ref="web.context" />
<property name="handler" ref="web.handler" />
<property name="contextPath" value="${webapp.contextPath}" />
<property name="virtualHosts" value="${webapp.virtualHosts}" />
</bean>
<bean id="web.handler" class="com.myapp.Application" />
</beans>
change the web.handler bean in your red5-web.xml file
<bean id="web.handler" class="com.myapp.Application"
singleton="true" autowire="byName" />
Check the other bean names also. The error you posted says same ID used for two or more beans.