PySide: Create popup based on location of button and window's edge - popup

I'd like to create a popup at the position of a clicked button and also offset that popup along the left edge of the existing window.
Right now I'm getting the position of the button fine, but it seems that the position of the window is off a little because when the popup is created it's about 200 pixels off to the left. I've commented the relevant sections below in my code. Thanks for any help/critiques.
from PySide import QtCore, QtGui
from shiboken import wrapInstance
def get_parent():
ptr = mui.MQtUtil.mainWindow()
return wrapInstance( long( ptr ), QtGui.QWidget )
############################################
class Tool_Window(QtGui.QDialog):
def __init__(self, parent = get_parent() ):
super(Tool_Window, self).__init__(parent)
self.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
# Commands
self.move_UI()
self.create_gui()
self.create_layout()
self.create_connections()
#-------------------------------------------
def create_gui(self):
self.button1 = QtGui.QPushButton()
self.button1.setMaximumWidth(50)
self.button2 = QtGui.QPushButton()
self.button2.setMaximumWidth(50)
self.button3 = QtGui.QPushButton()
self.button3.setMaximumWidth(50)
#-------------------------------------------
def create_layout(self):
layout = QtGui.QVBoxLayout()
layout.addWidget(self.button1)
layout.addWidget(self.button2)
layout.addWidget(self.button3)
layout.addStretch()
self.setLayout(layout)
#-------------------------------------------
def move_UI( self ):
''' Moves the UI to the cursor's position '''
pos = QtGui.QCursor.pos()
self.move(pos.x()+20, pos.y()+15)
#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#
def create_connections(self):
# Left click
self.button1.clicked.connect( self.on_left_click1 )
self.button2.clicked.connect( self.on_left_click2 )
self.button3.clicked.connect( self.on_left_click3 )
# Right click delete
delete = QtGui.QAction(self)
delete.setText("remove")
delete.triggered.connect(self.remove_button)
self.addAction(delete)
#-----#-----#-----#-----#-----#-----#-----#-----#-----#
def remove_button(self):
self.deleteLater()
def on_left_click1(self):
self.popup = Popup_Window(self, self.button1 ) # Passing button in so I can get it's position
self.popup.show()
def on_left_click2(self):
self.popup = Popup_Window(self, self.button2 )
self.popup.show()
def on_left_click3(self):
self.popup = Popup_Window(self, self.button3 )
self.popup.show()
############################################
class Popup_Window( QtGui.QDialog ):
def __init__( self, toolWindow, button ):
super( Popup_Window, self ).__init__()
self.button_pos = button # Creating variable for the button
self.toolWindow= mainUIWindow
self.setAttribute( QtCore.Qt.WA_DeleteOnClose )
#self.setMinimumWidth(100) # I need a minimum width
# Commands
self.create_gui()
self.create_layout()
self.create_connections()
self.move_UI()
#-------------------------------------------
def move_UI( self ): # Move popup based on pos of window and buttons
''' Moves the UI to the cursor's position '''
self.setWindowFlags(QtCore.Qt.Popup)
self.line_edit.setFocus()
# Get button position
btn_global_point = self.button_pos.mapToGlobal(self.button_pos.rect().topLeft())
# Get window position
win_global_point = self.mapToGlobal(self.rect().topLeft())
self.move(btn_global_point - win_global_point) # Here is where I find the distance between the window edge and button edge
#-------------------------------------------
def create_gui( self ):
''' Visible GUI stuff '''
self.my_label = QtGui.QLabel("default text")
self.line_edit = QtGui.QLineEdit()
self.line_edit.setMaxLength( 30 )
self.push_btn = QtGui.QPushButton( "Hey" )
self.push_btn.setMaximumWidth( 30 )
#-------------------------------------------
def create_layout( self ):
self.button_layout = QtGui.QVBoxLayout()
self.button_layout.addWidget( self.my_label )
self.button_layout.addWidget( self.line_edit )
self.button_layout.addWidget( self.push_btn )
self.setLayout(self.button_layout)
#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#
def create_connections( self ):
self.line_edit.textChanged.connect( self.on_text_changed )
#-----#-----#-----#-----#-----#-----#-----#-----#-----#
def on_text_changed( self ):
typed_name = self.line_edit.text()
self.my_label.setText(typed_name)
if __name__ == '__main__':
# Things to fix PySide Maya bug
try:
test_ui.close()
test_ui.deleteLater()
except:
pass
test_ui = Tool_Window()
test_ui.show()
try:
test_ui.show()
except:
test_ui.close()
test_ui.deleteLater()
Solution:
# Get button position
btn_global_point = self.button_pos.mapToGlobal(self.button_pos.rect().topLeft())
# Get window position
win_global_point = self.toolWindow.mapToGlobal(self.rect().topLeft())
self.move(win_global_point.x(), btn_global_point.y())

If I understand what you want to achieve, you have to keep only the y-value of button position and the x-value of window position.
So try this code:
# Get y button position
btn_global_point_y = self.button_pos.mapToGlobal(self.button_pos.rect().topLeft()).y()
# Get window position
win_global_point_x = self.mapToGlobal(self.rect().topLeft()).x()
self.move(win_global_point_x, btn_global_point_y)
With this lines you move the popup window at the height of the button and snap it to the left edge of the window.

Related

How to use ChosenInlineResultHandler in python telegram bot to handle the send query result?

Here is my code.
def start(update, context):
buttons = [InlineKeyboardButton("Invite User", switch_inline_query="test")]
update.message.reply_text("Please choose: ", reply_markup=InlineKeyboardMarkup(buttons))
def button(update, context):
query = update.callback_query
print(query)
def main():
updater = Updater(token, use_context=True)
updater.dispatcher.add_handler(ChosenInlineResultHandler(button))
And I set the bot inline feedback 100%, but in that case I can not send the message to the selected chat.
I'd like to send the button with the switch inline query, but I can not.
Here is my new code:
import logging
import os
from unittest import result
from telegram import ReplyKeyboardMarkup, InlineQueryResultArticle, KeyboardButton, InlineKeyboardButton, InlineKeyboardMarkup, WebAppInfo, Update, LoginUrl
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, ContextTypes, CallbackQueryHandler, ChosenInlineResultHandler, InlineQueryHandler
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
logger = logging.getLogger(__name__)
invite_state = False
def start(update, context):
"""Send a message when the command /start is issued."""
buttons = [
[InlineKeyboardButton(
text="Random Image",
switch_inline_query="test"
),
InlineKeyboardButton(
"Random Person",
callback_data="2"
)],
]
update.message.reply_text("Please choose:", reply_markup=InlineKeyboardMarkup(buttons))
def button (update, context):
query = update.inline_query.query
results = [
InlineQueryResultArticle(
id=str(uuid4()),
title="Caps",
input_message_content=InputTextMessageContent(query.upper()),
)
]
update.inline_query.answer(results)
def main(receiver_id):
updater = Updater(os.environ['TELEGRAM_BOT_TOKEN'] , use_context=True)
updater.bot.send_message(chat_id=receiver_id, text="welcome")
dp = updater.dispatcher
dp.add_handler(CommandHandler("start", start))
dp.add_handler(InlineQueryHandler(button))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
But I got error message "Can not find chat" in button function.
I totally solved this problem by using InlineQueryHandler.
So I send the answer with InlineQueryResultArticle and reply_markup with InlineButtons.
Here is the code.
def button (update, context):
query = update.inline_query.query
buttons = [[InlineKeyboardButton("Invitation", login_url=LoginUrl(url=websiteUrl))]]
results = [
InlineQueryResultArticle(
id=str("123456787654321"),
title="Send invitation",
input_message_content=InputTextMessageContent(query),
reply_markup=InlineKeyboardMarkup(buttons)
)
]
update.inline_query.answer(results)
Updater.dispatcher.add_handler(InlineQueryHandler(button))

object has no attribute 'dlg'

I'm trying to create a plugin for a Uni-subject which will receive a zipcode from a user and return the name of the corresponding location.
I have created the plugin layout, through the Plugin Builder and have designed the graphical interface with QtDesigner https://i.stack.imgur.com/h6k6Q.png . I have also added the .txt file that contains the zipcodes database to the plugin folder.
However, when I reload the plugin it gives me the error "object has no attribute 'dlg'" error message
Could you give me some guidance here and point me to where the problem could be? I am new to plugin development and python. Thanks
The code is this one:
import os
import sys
import qgis.core
from qgis.PyQt import uic
from qgis.PyQt import (
QtCore,
QtWidgets
)
import geocoder
# This loads your .ui file so that PyQt can populate your plugin with the elements from Qt Designer
FORM_CLASS, _ = uic.loadUiType(os.path.join(
os.path.dirname(__file__), 'example_dialog_base.ui'))
class ExampleDialog(QtWidgets.QDialog, FORM_CLASS):
POSTAL_CODES_PATH = ":/plugins/example/todos_cp.txt"
def __init__(self, parent=None):
"""Constructor."""
super(ExampleDialog, self).__init__(parent)
# Set up the user interface from Designer through FORM_CLASS.
# After self.setupUi() you can access any designer object by doing
# self.<objectname>, and you can use autoconnect slots - see
# http://qt-project.org/doc/qt-4.8/designer-using-a-ui-file.html
# #widgets-and-dialogs-with-auto-connect
self.setupUi(self)
#self.QpushButton.clicked.connect(self.print_hello_world)
self.QlineEdit.textChanged.connect(self.toggle_find_button)
self.find_code_btn.clicked.connect(self.execute)
#def print_hello_world(self):
#print('Hello World!')
def toggle_find_button(self):
if self.QlineEdit.text() == "":
self.find_code_btn.setEnabled(False)
else:
self.find_code_btn.setEnabled(True)
def find_record(self, main_code, extension):
file_handler = QtCore.QFile(self.POSTAL_CODES_PATH)
file_handler.open(QtCore.QIODevice.ReadOnly)
stream = QtCore.QTextStream(file_handler)
while not stream.atEnd():
line = stream.readLine()
info = line.split(";")
code1 = info[-3]
code2 = info[-2]
if code1 == main_code and code2 == extension:
result = info
break
else:
raise RuntimeError("Sem resultados")
return result
def handle_layer_creation(self, record):
place_name = record[3]
point = geocode_place_name(place_name)
print("lon: {} - lat: {}".format(point.x(), point.y()))
layer = create_point_layer(
point,
f"found_location_for_{record[-3]}_{record[-2]}",
place_name
)
current_project = qgis.core.QgsProject.instance()
current_project.addMapLayer(layer)
def show_error(self, message):
message_bar = self.iface.messageBar()
message_bar.pushMessage("Error", message, level=message_bar.Critical)
def validate_postal_code(raw_postal_code):
code1, code2 = raw_postal_code.partition("-")[::2]
if code1 == "" or code2 == "":
raise ValueError(
"Incorrect postal code: {!r}".format(raw_postal_code))
return code1, code2
def geocode_place_name(place_name):
geocoder_object = geocoder.osm(place_name)
lon = geocoder_object.json.get("lng")
lat = geocoder_object.json.get("lat")
if lat is None or lon is None:
raise RuntimeError(
"Could not retrieve lon/lat for "
"place: {!r}".format(place_name)
)
point = qgis.core.QgsPointXY(lon, lat)
return point
def create_point_layer(point, layer_name, place_name):
layer = qgis.core.QgsVectorLayer(
"Point?crs=epsg:4326&field=address:string(100)",
layer_name,
"memory"
)
provider = layer.dataProvider()
geometry = qgis.core.QgsGeometry.fromPointXY(point)
feature = qgis.core.QgsFeature()
feature.setGeometry(geometry)
feature.setAttributes([place_name])
provider.addFeatures([feature])
layer.updateExtents()
return layer

Qgis Plugin QgsMapToolEmitPoint QgsMapToolIdentifyFeature initialization

I'm working on a custom plugin in Qgis 3.22.3 Qt 5.15.2. My goal is to have a tool run when I click on a button in my dock widget that can either identify or select features from a layer so I can pass those attributes to a database function. I have tried creating subclasses of both QgsMapToolEmitPoint and QgsMapToolIdentifyFeature and the init method does get called but the button 'does nothing'. Slightly modifying my code to create a subclass of "QgsMapTool" does in fact start the tool and responds to logging from canvasPress events, etc. I'm still new to Qgis and figuring out how everything plays together, so I'm not sure if I can return features from QgsMaptool or not. I would love it if someone could help offer some suggestions or guidance because I haven't been able to find clarity, and any examples I've tried modifying seem like standalone scripts that are run directly from Qgis. Here is where my buttons connect(which gets called in init_gui), the subclass definition, and the function that gets called on button push. Code is very messy because of all the different iterations I've tried, but left it all here in case I have the right pieces. Again any leads would be helpful.
def connect_the_buttons(self):
# # get spots
b = self.dock.select_spots_tool
b.setEnabled(True)
b.setCheckable(True)
b.clicked.connect(self.getSpots)
def getSpots(self, checked):
if checked:
spot_id_List.clear()
t = self.selectSpots(self.iface)
#t = gs.selectSpots(self.iface)
self.iface.mapCanvas().setMapTool(t)
QApplication.setOverrideCursor(Qt.CrossCursor)
spots = QgsProject.instance().mapLayersByName('spots')[0]
self.iface.setActiveLayer(spots)
tType = type(t)
log(f'what is t? >> {type(t)}')
log(f'{tType}')
log(f'type({t})')
log(f'{self.selectSpots}')
else:
log('not checked')
QApplication.restoreOverrideCursor()
spot_id_List.clear()
class selectSpots(QgsMapToolEmitPoint):
#canvasClicked = pyqtSignal('QgsPointXY')
# def __new__(cls, *args, **kwargs):
# return super(selectSpots, cls).__new__(cls, *args, **kwargs)
def __init__(self, canvas):
log('selectSpots __init__ function is running...')
self.canvas = self.iface.mapCanvas()
#QgsMapTool.__init__(self, canvas)
#self.layer = self.iface.activeLayer()
#self.iface.canvasClicked.connect(self.id_spots)
#c = iface.mapCanvas()
#activeSpots = iface.activeLayer()
QgsMapToolEmitPoint.__init__(self, self.canvas)
#self.iface.layer().connect(self.getLayerId)
#self.iface.currentLayerChanged.connect(self.active_changed)
#QApplication.setOverrideCursor(Qt.CrossCursor)
# # def getLayerId(self):
# # log('connected_to_click layer event')
# # # def id_spots(self):
# # # log('this happend when i clicked')
def activate(self):
log('The activate method was called.')
def canvasDoubleClickEvent(self, e):
log('Double Clicked')
log(f'double click event: {e}')
# # def active_changed(self, layer):
# # activeSpots.removeSelection()
# # spot_id_List.clear()
def canvasReleaseEvent(self, event):
log('canvas release event recorded')
def canvasPressEvent(self, event):
log('canvas press event recorded')
point = event.mapPoint()
self.canvasClicked.emit(point)
log(f'point: {point}')
# # log(f'event: {event}')
# # #self.handle_spot_selection()
# # log(f'on press: spot_id_List: {spot_id_List}')
# # # selectedLayer = self.iface.activeLayer()
# # # selection = selectedLayer.selectedFeatures()
# # #self.iface.actionSelect().trigger()
# # for f in selection:
# # spot_id_List.append(f.attribute('id'))
# # log(f'after press: spot_id_List: {spot_id_List}')

How to get filepath from droped file with pyqt5?

I want to get path of the file dropped on QLabel. So I code like this, but label doesn't accept the file. What is the problem..?
Here is my code. So long code sorry and thank you!
import random
import sys
import pygame
import time
from PyQt5.QtGui import QPixmap
from PyQt5.QtCore import Qt, QTimer
from PyQt5.QtWidgets import QWidget, QLabel, QApplication, QDesktopWidget
class Example(QWidget):
size=100
imgNum=0
frameCount=4
isXmin = False
isXmax = False
isYmin = False
isYmax = False
isLeft= True
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
sizeObject = QDesktopWidget().screenGeometry()
# print(" Screen size : " + str(sizeObject.height()) + "x" + str(sizeObject.width()))
self.xMax=sizeObject.width()-10
self.yMax=sizeObject.height()-10
print(self.xMax)
print(self.yMax)
self.setWindowFlags(Qt.FramelessWindowHint)
self.setAttribute(Qt.WA_TranslucentBackground)
self.setStyleSheet("background-color:transparent;")
self.setGeometry(100, 100, 100, 100)
self.setWindowFlags(Qt.SplashScreen | Qt.WindowStaysOnTopHint)
self.setAcceptDrops(True)
self.label=QLabel(self)
self.label.setAcceptDrops(True)
self.pixmaps=[QPixmap('left.png'),QPixmap('stand.png'),QPixmap('right.png'),QPixmap('stand.png'),QPixmap('leftR.png'),QPixmap('standR.png'),QPixmap('rightR.png'),QPixmap('standR.png')]
for x in range(len(self.pixmaps)):
self.pixmaps[x]=self.pixmaps[x].scaled(self.size,self.size,Qt.KeepAspectRatio)
self.resize(self.pixmaps[2].width(),self.pixmaps[2].height())
self.label.setPixmap(self.pixmaps[len(self.pixmaps)-1])
self.changeTimer=QTimer(self)
self.changeTimer.timeout.connect(self.changeFoot)
self.moveTimer=QTimer(self)
self.moveTimer.timeout.connect(self.moving)
self.setAcceptDrops(True)
pygame.init()
pygame.mixer.music.load('hoi_imtemmie.mp3')
pygame.mixer.music.play()
self.show()
def dragEnterEvent(self, event):
if event.mimeData().hasUrls:
event.accept()
else:
event.ingore()
def dropEvent(self, event):
self.path=event.mimeData.urls()
def moving(self):
if self.distance == 0:
print(self.distance)
print(self.x(),"x",self.y())
self.label.setPixmap(self.pixmaps[1])
self.moveTimer.stop()
self.changeTimer.stop()
time.sleep(3)
self.setMovement()
return 0
else:
self.move(self.x()+self.direct[0],self.y()+self.direct[1])
self.distance-=1
if self.x()<=-10 :
self.distance=0
print("xm")
self.isXmin = True
if self.y()<=-10 :
self.distance=0
print("ym")
self.isYmin = True
if self.x()>=self.xMax:
self.distance=0
print("xM")
self.isXmax=True
if self.y()>=self.yMax :
self.distance=0
print("yM")
self.isYmax=True
def setMovement(self):
self.direct=[0,0]
while(self.direct[0]==0 and self.direct[1]==0):
self.direct=[random.randint(-1,1),random.randint(-1,1)]
if self.isXmax:
self.direct[0]=-1
if self.isXmin:
self.direct[0]=1
if self.isYmin:
self.direct[1]=1
if self.isYmax:
self.direct[1]=-1
if self.direct[0]== -1:
self.isLeft=True
self.imgNum=0
elif self.direct[0]== 1:
self.isLeft=False
self.imgNum=4
self.isXmax = False
self.isXmin = False
self.isYmin = False
self.isYmax = False
# if direct[0]*direct[1]==0 : self.delta = QPoint(dX*direct[0],dY*direct[1])
# else: self.delta=QPoint(direct[0]*(dX**(1/2)),direct[1]*(dY**1/2))
self.distance=random.randint(200,400)
self.changeTimer.start(300)
self.moveTimer.start(30)
def changeFoot(self):
self.label.setPixmap(self.pixmaps[self.imgNum])
if self.isLeft:
if self.imgNum<self.frameCount-1:
self.imgNum+=1
else :
self.imgNum=0
else:
if self.imgNum<2*self.frameCount-1:
self.imgNum+=1
else :
self.imgNum=self.frameCount
def mousePressEvent(self, QMouseEvent):
self.setMovement()
pygame.mixer.music.load('hoi_imtemmie.mp3')
pygame.mixer.music.play()
def keyPressEvent(self, QKeyEvent):
if QKeyEvent.key() == Qt.Key_Escape:
sys.exit()
# if QKeyEvent.key() == Qt.Key_G:
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
i set AcceptDrops(True)
self.setAcceptDrops(True)
and code about get filepath ▼
def dragEnterEvent(self, event):
if event.mimeData().hasUrls:
event.accept()
else:
event.ingore()
def dropEvent(self, event):
self.path=event.mimeData.urls()
Try to loop through event.mimeData().urls()
for url in event.mimeData().urls():
self.path = url.toLocalFile()

how to access variable from another class in python

I would like to access variable lotId & qty_selected in class 'InputDialog' and to be use in class 'Mainwindow'. I did tried to find a solution in net but unable to solve it until now. can anyone show how to make it?
Here is my current code:
from __future__ import division
from skimage.measure import compare_ssim as ssim
import matplotlib.pyplot as plt
import numpy as np
import sys
import os, glob
import cv2
from PyQt4 import QtCore, QtGui, uic
from PyQt4.QtGui import *
from inputdialog import Ui_inputDialog
from mainwindow import Ui_mainWindow
from tkinter import messagebox
class MainWindow(QtGui.QMainWindow, Ui_mainWindow):
def __init__(self, class_input):
QtGui.QMainWindow.__init__(self)
Ui_mainWindow.__init__(self)
Ui_inputDialog.__init__(self)
self.setupUi(self)
self.capture_button.clicked.connect(self.captureImage)
self.display_button.clicked.connect(self.displayImage)
self.deviceBox.activated.connect(self.selectDeviceCombo)
self.startInspectionBtn.clicked.connect(self.enterLotID)
self.display_button.clicked.connect(self.displayResults)
#self.viewResultBtn.clicked.connect(self.viewResults)
self.window2 = None
def enterLotID(self): # Dialog box will ask user to enter lot ID and wafer qty
if self.window2 is None:
self.window2 = InputDialog(self)
self.window2.isModal()
self.window2.show()
# Program need to be loop through a image file in directory
def displayImage(self, ):
os.chdir('c:\\Users\\mohd_faizal4\\Desktop\\Python\\Testing' + '\\' + lotId )
for lotId in glob.glob('*.jpeg'):
print(lotId)
sample_label = 'c:/Users/mohd_faizal4/Desktop/Python/Image/Picture 6.jpg' # Sample image must read from current folder lot ID running the inspection
self.sample_label.setScaledContents(True)
self.sample_label.setPixmap(QtGui.QPixmap(sample_label))
def selectDeviceCombo(self):
self.var_Selected = self.deviceBox.currentText()
#print('The user selected value now is:')
print('Device = ' + self.var_Selected)
if self.var_Selected.lower() == 'xf35':
print("Great! Device Id is - " + self.var_Selected + '!')
source_label ='c:/Users/mohd_faizal4/Desktop/Python/Image/Picture 4.jpg'
self.source_label.setScaledContents(True)
self.source_label.setPixmap(QtGui.QPixmap(source_label))
elif self.var_Selected.lower() == 'xf38':
print("Great! Device Id is - " + self.var_Selected + '!')
source_label ='c:/Users/mohd_faizal4/Desktop/Python/Image/Picture 5.jpg'
self.source_label.setScaledContents(True)
self.source_label.setPixmap(QtGui.QPixmap(source_label))
elif self.var_Selected.lower() == 'x38c':
print("Great! Device Id is - " + self.var_Selected + '!')
source_label ='c:/Users/mohd_faizal4/Desktop/Python/Image/Picture 7.jpg'
self.source_label.setScaledContents(True)
self.source_label.setPixmap(QtGui.QPixmap(source_label))
else:
print("Pls select device id. It's compulsory field!")
def captureImage(self): # Capture image and display on 'Sample' column under Inspection
cam = cv2.VideoCapture(0)
i = 1
while i < int(input(qty_selected)):
ret, frame = cam.read()
cv2.imshow('Please review an image', frame)
if not ret:
break
k = cv2.waitKey(0)
if k%256 == 27:
# ESC pressed
print("Escape hit, closing...")
break
if k % 256 == 32:
# SPACE pressed
img_name = "_{}.jpeg".format(i)
#print (img_name)
cv2.imwrite(img_name, frame)
#cv2.imwrite(os.path.join(dirname, img_name), frame)
print("{}".format(img_name))
i += 1
cam.release()
cv2.destroyAllWindows()
def displayResults(self): #Display image of wafer at 'Result' tab. Simultaneously with 'Inspect'
label_vid01 = 'c:/Users/mohd_faizal4/Desktop/Python/Image/Picture 7.jpg'
self.label_vid01.setScaledContents(True)
self.label_vid01.setPixmap(QtGui.QPixmap(label_vid01))
# A new class for user input dialog to enter lot information
class InputDialog (QtGui.QDialog, Ui_inputDialog):
def __init__(self, parent):
QtGui.QWidget.__init__(self, parent)
self.setupUi(self)
self.okButton.clicked.connect(self.addLotId)
self.okButton.clicked.connect(self.selectWaferQty)
def addLotId(self):
lotId = str(self.strLotId.toPlainText())
self.strLotId.setText(lotId)
print(lotId)
path = 'c:\\Users\\mohd_faizal4\\Desktop\\Python\\Testing' + '\\' + lotId
if not os.path.exists(path):
os.makedirs(path)
else:
messagebox.showwarning('Error','Please enter required information')
QtGui.QMessageBox.show(self)
# User require to select wafer quantity upon enter the lot ID
def selectWaferQty(self):
qty_selected = self.waferQty.currentText()
#print ('The user selected value now is:')
print ('Wafer Qty = ' + qty_selected)
#if self.qty_selected() == '1':
# print('Great! Wafer Qty is - ' + self.qty_selected + '!')
#else:
# print ('Pls select wafer quantity!')
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
Window = MainWindow()
Window.show()
sys.exit()
Under the class InputDialog, change lotId and qty_selected to self.lotId and self.qty_selected, respectively. And to access it inside your WindowMain class, try self.window2.lotId and self.window2.qty_selected.