I am building a GUI for obtaining user inputs and then using them in some complex step later. I have a group of checkboxes from which the user has to choose at least one and also provide an 'alias' name for it in the QLineEdit right below the checkbox (default name is taken otherwise).
Currently, I have to first enter the alias name and then check the checkbox to register the entered name in the line edit to get the value entered by the user and connected checkbox name. This order is not normal.
Is there a way to get the Editline data and the connected checkbox name when 'Continue' is clicked?
Here is my code:
from PyQt4 import QtGui, QtCore
import sys
checkpoint_list = ['Amsterdam','Munich','Paris','Mumbai']
class MyGui(QtGui.QWidget):
def __init__(self):
super(MyGui, self).__init__()
self.initUI()
self.final_list = []
self.platform_list = {}
self.qem = None
def initUI(self):
lay_out = QtGui.QVBoxLayout(self)
# select the CPs
cp_lbl = QtGui.QLabel("Please select CP versions to compare:", self)
lay_out.addWidget(cp_lbl)
self.cb = []
self.platform_label = []
i = 0
for cp in checkpoint_list:
self.cb.append(QtGui.QCheckBox(cp, self))
self.platform_label.append(QtGui.QLineEdit(cp, self))
self.cb[i].stateChanged.connect(self.clickBoxStateChanged)
lay_out.addWidget(self.cb[i])
lay_out.addWidget(self.platform_label[i])
i += 1
lay_out.addStretch(10)
# Continue and cancel button
btn_cancel = QtGui.QPushButton('Cancel', self)
btn_continue = QtGui.QPushButton('Continue', self)
hbox = QtGui.QHBoxLayout()
hbox.addStretch()
hbox.addWidget(btn_continue)
hbox.addWidget(btn_cancel)
vbox = QtGui.QVBoxLayout()
vbox.addStretch()
lay_out.addLayout(hbox)
lay_out.addLayout(vbox)
self.setLayout(lay_out)
btn_cancel.clicked.connect(self.onclick_cancel)
btn_cancel.setToolTip('To <b>Cancel</b> with this process')
btn_continue.clicked.connect(self.onclick_Continue)
btn_continue.setToolTip('To <b>Continue</b> with the matching')
# Screen show
self.setGeometry(300, 300, 500, 400)
self.setWindowTitle('CP Selection Window')
self.show()
def clickBoxStateChanged(self, cb):
self.final_list = []
self.platform_list = {}
for i in range(len(self.cb)):
if self.cb[i].isChecked():
if self.cb[i] not in self.final_list:
self.final_list.append(str(self.cb[i].text()))
self.platform_list[str(self.cb[i].text())] = str(self.platform_label[i].text())
print self.final_list
print self.platform_list
elif self.cb[i].isChecked() == False:
if self.cb[i].text() in self.final_list:
self.final_list.remove(str(self.cb[i].text()))
del self.platform_list[str(self.cb[i].text())]
print self.final_list
print self.platform_list
def onclick_Continue(self):
try:
if len(self.final_list) == 0:
self.qem = QtGui.QErrorMessage(self)
self.qem.showMessage("Please select at least 1 checkpoint to continue...")
else:
self.close()
except:
print "No CP was selected..."
def onclick_cancel(self):
sys.exit()
if __name__ == "__main__":
# GUI code
app = QtGui.QApplication(sys.argv)
w = MyGui()
app.exec_()
The simplest solution is to create a method that analyzes the information and that returns a dictionary of the selected elements:
class MyGui(QtGui.QWidget):
def __init__(self):
super(MyGui, self).__init__()
self.initUI()
def initUI(self):
lay_out = QtGui.QVBoxLayout(self)
# select the CPs
cp_lbl = QtGui.QLabel("Please select CP versions to compare:")
lay_out.addWidget(cp_lbl)
self.cb = []
self.platform_label = []
for cp in checkpoint_list:
cb = QtGui.QCheckBox(cp)
le = QtGui.QLineEdit(cp)
lay_out.addWidget(cb)
lay_out.addWidget(le)
self.cb.append(cb)
self.platform_label.append(le)
lay_out.addStretch(10)
# Continue and cancel button
btn_cancel = QtGui.QPushButton("Cancel")
btn_continue = QtGui.QPushButton("Continue")
hbox = QtGui.QHBoxLayout()
hbox.addStretch()
hbox.addWidget(btn_continue)
hbox.addWidget(btn_cancel)
vbox = QtGui.QVBoxLayout()
vbox.addStretch()
lay_out.addLayout(hbox)
lay_out.addLayout(vbox)
btn_cancel.clicked.connect(self.onclick_cancel)
btn_cancel.setToolTip("To <b>Cancel</b> with this process")
btn_continue.clicked.connect(self.onclick_Continue)
btn_continue.setToolTip("To <b>Continue</b> with the matching")
# Screen show
self.setGeometry(300, 300, 500, 400)
self.setWindowTitle("CP Selection Window")
self.show()
def get_elements_selected(self):
values_selected = dict()
for cb, le in zip(self.cb, self.platform_label):
if cb.isChecked():
values_selected[cb.text()] = le.text()
return values_selected
def onclick_Continue(self):
values = self.get_elements_selected()
if values:
print(values)
self.close()
else:
qem = QtGui.QErrorMessage(self)
qem.showMessage("Please select at least 1 checkpoint to continue...")
qem.exec_()
def onclick_cancel(self):
sys.exit()
Related
I want to run a AnimationGroup with different changing animations.
But the problem is that the function clear()
self.group = QtCore.QSequentialAnimationGroup(self)
def anim(self):
if X == True:
self.group.addAnimation(self.animation_1)
self.group.addAnimation(self.animation_2)
elif X == False:
self.group.addAnimation(self.animation_3)
self.group.addAnimation(self.animation_4)
self.group.start()
self.group.clear()
displays an error
RuntimeError: wrapped C/C++ object of type QVariantAnimation has been deleted
I can’t constantly create a new group.
def anim(self):
self.group = QtCore.QSequentialAnimationGroup(self)
if X == True:
self.group.addAnimation(self.animation_1)
self.group.addAnimation(self.animation_2)
elif X == False:
self.group.addAnimation(self.animation_3)
self.group.addAnimation(self.animation_4)
self.group.start()
self.group.clear()
I tried to use removeAnimation
import sys
from PyQt5 import QtWidgets, QtGui, QtCore
class Rad(QtWidgets.QWidget):
def __init__(self, group, pos, parent=None):
super(Rad, self).__init__(parent)
self.resize(50, 50)
lay = QtWidgets.QVBoxLayout(self)
self.radio = QtWidgets.QRadioButton()
self.label = QtWidgets.QLabel()
self.label.setText('but-{}'.format(pos))
self.group = group
self.pos = pos
lay.addWidget(self.radio)
lay.addWidget(self.label)
self.radio.toggled.connect(self.fun)
self.animation = QtCore.QVariantAnimation()
self.animation.setDuration(1000)
self.animation.valueChanged.connect(self.value)
self.animation.setStartValue(100)
self.animation.setEndValue(0)
self.can = False
def value(self, val):
self.move(self.pos, val)
def fun(self):
self.animation.setStartValue(
100
if not self.can
else 0
)
self.animation.setEndValue(
0
if not self.can
else 100
)
if self.group.animationAt(1) == None :
print("Bad")
else :
print("Good")
self.group.removeAnimation(self.group.animationAt(0))
self.group.addAnimation(self.animation)
self.group.start()
self.can = not self.can
class Test(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.group = QtCore.QSequentialAnimationGroup(self)
self.buts = QtWidgets.QButtonGroup(self, exclusive=True)
wid_1 = Rad(self.group, 200, self)
wid_2 = Rad(self.group, 100, self)
wid_3 = Rad(self.group, 0, self)
self.buts.addButton(wid_1.radio, 0)
self.buts.addButton(wid_2.radio,1)
self.buts.addButton(wid_3.radio, 2)
wid_1.setStyleSheet('background:brown;')
wid_2.setStyleSheet('background:yellow;')
wid_3.setStyleSheet('background:green;')
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
w = Test()
w.resize(500, 500)
w.show()
sys.exit(app.exec_())
And now the animation has become sharp
And in the console output
QAnimationGroup::animationAt: index is out of bounds
From what I can deduce is that you want the pressed item to move down and if any item was in the low position then it must return to its position. If so then my answer should work.
You should not use the clear method since that removes and deletes the animation, instead use takeAnimation(0) until there are no animations, and just add the new animations, but that logic should not be inside "Rad" but in the Test class:
import sys
from PyQt5 import QtWidgets, QtGui, QtCore
class Rad(QtWidgets.QWidget):
def __init__(self, text, parent=None):
super(Rad, self).__init__(parent)
self.resize(50, 50)
self.radio = QtWidgets.QRadioButton()
self.label = QtWidgets.QLabel()
self.label.setText(text)
lay = QtWidgets.QVBoxLayout(self)
lay.addWidget(self.radio)
lay.addWidget(self.label)
self.animation = QtCore.QVariantAnimation()
self.animation.setDuration(1000)
self.animation.valueChanged.connect(self.on_value_changed)
self.animation.setStartValue(100)
self.animation.setEndValue(0)
#QtCore.pyqtSlot("QVariant")
def on_value_changed(self, val):
pos = self.pos()
pos.setY(val)
self.move(pos)
def swap_values(self):
self.animation.blockSignals(True)
start_value = self.animation.startValue()
end_value = self.animation.endValue()
self.animation.setStartValue(end_value)
self.animation.setEndValue(start_value)
self.animation.blockSignals(False)
class Test(QtWidgets.QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.buts = QtWidgets.QButtonGroup(self, exclusive=True)
wid_1 = Rad("but-200", self)
wid_1.setStyleSheet("background:brown;")
wid_1.move(200, 0)
wid_2 = Rad("but-100", self)
wid_2.setStyleSheet("background:yellow;")
wid_2.move(100, 0)
wid_3 = Rad("but-0", self)
wid_3.setStyleSheet("background:green;")
wid_3.move(0, 0)
self.buts.addButton(wid_1.radio, 0)
self.buts.addButton(wid_2.radio, 1)
self.buts.addButton(wid_3.radio, 2)
self.buts.buttonToggled.connect(self.on_button_toggled)
self.group = QtCore.QSequentialAnimationGroup(self)
self.last_widget = None
#QtCore.pyqtSlot(QtWidgets.QAbstractButton, bool)
def on_button_toggled(self, button, state):
if state:
wid = button.parent()
if self.group.animationCount() > 0:
self.group.takeAnimation(0)
if isinstance(self.last_widget, Rad):
self.last_widget.swap_values()
self.group.addAnimation(self.last_widget.animation)
wid.swap_values()
self.group.addAnimation(wid.animation)
self.group.start()
self.last_widget = wid
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
w = Test()
w.resize(500, 500)
w.show()
sys.exit(app.exec_())
How do I make sure that clicking on a QListWidget item opens the corresponding widgets in the QFrame and that the data entered in these widgets is saved between switching list items?
class Window(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
vbox = QVBoxLayout()
tab_widget = QTabWidget()
tab_widget.setStyleSheet('background-color:gainsboro')
tab_widget.addTab(Setup(), "setup")
vbox.addWidget(tab_widget)
self.setLayout(vbox)
class Setup(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
hbox = QHBoxLayout()
splitter = QSplitter(Qt.Horizontal)
self.list = QListWidget()
self.list.setStyleSheet("background-color:white")
QListWidgetItem("vertices", self.list)
QListWidgetItem("blocks", self.list)
self.list.itemClicked.connect(self.conv_met)
splitter.addWidget(self.list)
self.frame = QFrame()
self.frame.setFrameShape(QFrame.StyledPanel)
self.frame.setLineWidth(0.6)
splitter.addWidget(self.frame)
hbox.addWidget(splitter)
self.setLayout(hbox)
self.show()
def conv_met(self, item):
if item.text() == "vertices":
convertToMeters_layout = QHBoxLayout()
convertToMeters_lbl = QLabel("convertToMeters")
convertToMeters_val = QLineEdit("0.1")
convertToMeters_layout.addWidget(convertToMeters_lbl)
convertToMeters_layout.addWidget(convertToMeters_val)
self.frame.setLayout(convertToMeters_layout)
if item.text() == "blocks":
block_grad_layout = QGridLayout()
hexx = QComboBox(self)
hexx.addItems(["hex"])
ver_labels = QLineEdit("0 1 2 3 4 5 6 7")
block_grad_layout.addWidget(hexx, 0, 0)
block_grad_layout.addWidget(ver_labels, 0, 1)
self.frame.setLayout(block_grad_layout)
if __name__ == '__main__':
app = QApplication(sys.argv)
main_win = Window()
main_win.show()
sys.exit(app.exec_())
In order to keep data for an item, you can use setData(role, value) to store the previous entered data and before changing to the new current item.
Note that you should not use setLayout() more than once; in fact, your example doesn't work as expected for this reason, and you could see the error message if you run it from a shell or command prompt:
QWidget::setLayout: Attempting to set QLayout "" on QFrame "", which already has a layout
To achieve what you want, the solution is to use QStackedWidget, which works almost like a QTabWidget, but doesn't have a tab bar to switch between "pages", as they can only be changed programmatically using setCurrentIndex() or setCurrentWidget().
class Setup(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
hbox = QHBoxLayout()
splitter = QSplitter(Qt.Horizontal)
self.list = QListWidget()
self.list.setStyleSheet("background-color:white")
self.verticesItem = QListWidgetItem("vertices", self.list)
self.blocksItem = QListWidgetItem("blocks", self.list)
self.list.itemClicked.connect(self.conv_met)
splitter.addWidget(self.list)
self.frame = QFrame()
self.frame.setFrameShape(QFrame.StyledPanel)
self.frame.setLineWidth(0.6)
frameLayout = QVBoxLayout(self.frame)
self.stackedWidget = QStackedWidget()
frameLayout.addWidget(self.stackedWidget)
self.convertToMeters_widget = QWidget()
self.stackedWidget.addWidget(self.convertToMeters_widget)
convertToMeters_layout = QHBoxLayout(self.convertToMeters_widget)
convertToMeters_lbl = QLabel("convertToMeters")
self.convertToMeters_val = QLineEdit("0.1")
convertToMeters_layout.addWidget(convertToMeters_lbl)
convertToMeters_layout.addWidget(self.convertToMeters_val)
self.block_grad_widget = QWidget()
self.stackedWidget.addWidget(self.block_grad_widget)
block_grad_layout = QGridLayout(self.block_grad_widget)
hexx = QComboBox()
hexx.addItems(["hex"])
self.ver_labels = QLineEdit("0 1 2 3 4 5 6 7")
block_grad_layout.addWidget(hexx, 0, 0)
block_grad_layout.addWidget(self.ver_labels, 0, 1)
splitter.addWidget(self.frame)
hbox.addWidget(splitter)
self.setLayout(hbox)
self.currentItem = None
def conv_met(self, item):
if self.currentItem:
if self.currentItem == self.verticesItem:
self.currentItem.setData(Qt.UserRole, self.convertToMeters_val.text())
else:
self.currentItem.setData(Qt.UserRole, self.ver_labels.text())
if item == self.currentItem:
return
self.currentItem = item
if item == self.verticesItem:
self.stackedWidget.setCurrentWidget(self.convertToMeters_widget)
self.convertToMeters_val.setText(item.data(Qt.UserRole) or '0.1')
elif item == self.blocksItem:
self.stackedWidget.setCurrentWidget(self.block_grad_widget)
self.ver_labels.setText(item.data(Qt.UserRole) or '0 1 2 3 4 5 6 7')
Note that if you want to store numeric values for the "vertices", you might prefer to use a QSpinBox (or QDoubleSpinBox for floating numbers). Similarly, if you need only hexadecimal values, it's better to set an inputMask or add a validator to ensure that the entered values are valid.
I created a widget, The process of widget begins with an entering the SQL.table_name and switch the Run_analysis button to generate the output in the format of csv.file. the mentioned process performed well. but I stuck in printing the (print) statement in the larger textbox.
class EpiClass:
NR = 0
R = 0
CT = 0
def __init__(self, obj):
self.obj = obj
def epi_calc(self):
"""Function to process EPI formula"""
with open(FN, "w") as FL: #FN object FL
for j in self.obj:
if j[12] is not None and float(j[12]) != 0: #Exclude (Null, 0) values in Cre-j[12]
j12 = float(j[12])
type(j12)
#type(j[12]) #tested
#type(j[35]) #tested
{
Body of statement, assume it add two variable
}
print("Total no of rows affected:", EpiClass.CT)
print("No. of records not analysed:", EpiClass.NR)
print("No. of records analysed:", EpiClass.R)
Here we go to PyQt5.
class WinClass(QMainWindow):
"""Main Window"""
def __init__(self):
super().__init__()
self.title = 'EGFR Widget'
self.left = 10
self.top = 10
self.width = 1920
self.height = 1080
self.init_ui()
def init_ui(self):
"""Window Geometry"""
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
#label
# Create textbox
self.textbox = QLineEdit(self)
self.textbox.move(20, 20)
self.textbox.resize(280, 40)
# Create a button in the window
self.button = QPushButton('Run Analysis', self)
self.button.move(20, 80)
#Print affected Rows
self.textbox2 = QLineEdit(self)
self.textbox2.move(120, 120)
self.textbox2.resize(880, 140)
# connect button to function on_click
self.button.clicked.connect(self.on_click)
self.show()
#pyqtSlot()
def on_click(self):
"""Button Action function"""
tb_value = str(self.textbox.text())
new_class = Edb(tb_value)
new_class.eclass()
######Im messed up in this step to print that 3 statements in textbox2#############
tb2_value = str(self.textbox2.text(EpiClass.CT))
#tb3_value = str(self.textbox2.text(EpiClass.NR))
#tb4_value = str(self.textbox2.text(EpiClass.R))
if __name__ == '__main__':
APP = QApplication(sys.argv)
ex = WinClass()
sys.exit(APP.exec_())
Kindly suggest a code to resolve the print statement. Much thanks!
You're trying to write using a read-only method text, you should use setText instead. I would save those statements in some variable and access from your widget, but that's up to you. I hope it helps.
def on_click(self):
"""Button Action function"""
tb_value = "Total no of rows affected: {}".format(EpiClass.CT)
self.textbox2.setText(tb_value)
I have several tabs and inside the "admin" tab I want to display two pages: one locked page (before entering credentials) and another unlocked page (after successful login). To do this, I'm using a QStackedWidget() to switch between the two pages. I have created a locked login screen but can't seem to move the object to the center of the page.
I have looked at moving widgets inside QStackedWidget and centering widgets in the center of the screen but my objects do not seem to change position. I've tried to move the entire internal widget using move() to the center of the screen using the desktop dimension and the parent widget to no avail. How would I be able to move the login fields to the center of the page? Thanks!
Current:
Desired:
Code:
from PyQt4 import QtGui, QtCore
# from load_CSS import load_CSS
# from widgets import UniversalPlotWidget
import sys
import time
def exit_application():
"""Exit program event handler"""
sys.exit(1)
class VerticalTabBar(QtGui.QTabBar):
def __init__(self, width, height, parent=None):
super(VerticalTabBar, self).__init__(parent)
self.width = width
self.height = height
def tabSizeHint(self, index):
return QtCore.QSize(self.width, self.height)
def paintEvent(self, event):
painter = QtGui.QStylePainter(self)
tab_options = QtGui.QStyleOptionTab()
for tab in range(self.count()):
self.initStyleOption(tab_options, tab)
painter.drawControl(QtGui.QStyle.CE_TabBarTabShape, tab_options)
painter.save()
size = tab_options.rect.size()
size.transpose()
rectangle = QtCore.QRect(QtCore.QPoint(), size)
rectangle.moveCenter(tab_options.rect.center())
tab_options.rect = rectangle
center = self.tabRect(tab).center()
painter.translate(center)
painter.rotate(90)
painter.translate(-center)
painter.drawControl(QtGui.QStyle.CE_TabBarTabLabel, tab_options);
painter.restore()
class TabWidget(QtGui.QTabWidget):
def __init__(self, *args, **kwargs):
QtGui.QTabWidget.__init__(self, *args, **kwargs)
self.setTabBar(VerticalTabBar(kwargs.pop('width'), kwargs.pop('height')))
self.setTabPosition(QtGui.QTabWidget.West)
self.setTabShape(QtGui.QTabWidget.Rounded)
class AdminTabWidget(QtGui.QWidget):
def __init__(self, parent=None):
super(AdminTabWidget, self).__init__(parent)
self.setWindowModality(QtCore.Qt.ApplicationModal)
self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
self.admin_page_locked_init()
self.admin_page_unlocked_init()
self.admin_page_layout = QtGui.QGridLayout()
self.admin_page_switch = QtGui.QStackedWidget()
self.admin_page_switch.addWidget(self.admin_locked_tab)
self.admin_page_switch.addWidget(self.admin_unlocked_tab)
self.admin_page_switch.setCurrentIndex(0)
self.admin_page_layout.addWidget(self.admin_page_switch,0,0)
def admin_page_locked_init(self):
self.admin_locked_tab = QtGui.QWidget()
self.admin_locked_tab.setFixedSize(550,225)
self.admin_locked_layout = QtGui.QGridLayout()
self.username_label = QtGui.QLabel('Username: ')
self.username_field = QtGui.QLineEdit()
self.username_field.returnPressed.connect(self.verify_credentials)
self.space_label = QtGui.QLabel(' ')
self.space_label.setFixedHeight(25)
self.password_label = QtGui.QLabel('Password: ')
self.password_field = QtGui.QLineEdit()
self.password_field.returnPressed.connect(self.verify_credentials)
self.password_field.setEchoMode(QtGui.QLineEdit.Password)
self.verify_button = QtGui.QPushButton('Ok')
self.verify_button.clicked.connect(self.verify_credentials)
self.cancel_button = QtGui.QPushButton('Cancel')
self.cancel_button.clicked.connect(self.unauthorized)
self.status_label = QtGui.QLabel('')
self.status_label.setAlignment(QtCore.Qt.AlignCenter)
self.button_layout = QtGui.QGridLayout()
self.button_layout.addWidget(self.verify_button,0,0,1,1)
self.button_layout.addWidget(self.cancel_button,0,1,1,1)
self.admin_locked_layout.addWidget(self.username_label,0,0,1,1)
self.admin_locked_layout.addWidget(self.username_field,0,1,1,1)
self.admin_locked_layout.addWidget(self.space_label,1,0,1,3)
self.admin_locked_layout.addWidget(self.password_label,2,0,1,1)
self.admin_locked_layout.addWidget(self.password_field,2,1,1,1)
self.admin_locked_layout.addWidget(self.status_label,3,0,1,3)
self.admin_locked_layout.addLayout(self.button_layout,4,0,1,3)
self.admin_locked_tab.setLayout(self.admin_locked_layout)
def verify_credentials(self):
print('button pressed')
# Grab username/password from input fields
self.username = str(self.username_field.text())
self.password = str(self.password_field.text())
self.status_label.setText('Verifying')
self.status_label.setStyleSheet('QLabel {color: rgb(117,255,161)}')
self.spin(.001)
print('verified')
def spin(self, seconds):
"""Pause for set amount of seconds, replaces time.sleep so program doesnt stall"""
time_end = time.time() + seconds
while time.time() < time_end:
QtGui.QApplication.processEvents()
def unauthorized(self):
print('unauthorized')
self.status_label.setText('Invalid username and/or password')
self.status_label.setStyleSheet('QLabel {color: rgb(255,65,106)}')
def admin_page_unlocked_init(self):
self.admin_unlocked_tab = QtGui.QWidget()
admin_unlocked_layout = QtGui.QGridLayout()
admin_unlocked_button = QtGui.QPushButton('unlocked')
admin_unlocked_layout.addWidget(admin_unlocked_button)
self.admin_unlocked_tab.setLayout(admin_unlocked_layout)
def get_admin_page_layout(self):
return self.admin_page_layout
if __name__ == '__main__':
# Create main application window
app = QtGui.QApplication(sys.argv)
# app.setStyleSheet(load_CSS(1))
app.setStyle(QtGui.QStyleFactory.create("Cleanlooks"))
font = QtGui.QFont('Ubuntu', 20)
font.setWeight(70)
app.setFont(font)
screen_height = QtGui.QApplication.desktop().screenGeometry().height()
main_window_tab = TabWidget(width=300, height=screen_height/8)
main_window_tab.setWindowTitle("Tab Layout")
main_window_tab.setWindowFlags(QtCore.Qt.FramelessWindowHint)
main_window_tab.showMaximized()
tab1 = QtGui.QWidget()
tab2 = QtGui.QWidget()
tab3 = QtGui.QWidget()
tab4 = QtGui.QWidget()
tab5 = QtGui.QWidget()
tab6 = QtGui.QWidget()
tab7 = QtGui.QWidget()
admin_tab = QtGui.QWidget()
admin_tab_widget = AdminTabWidget()
admin_tab.setLayout(admin_tab_widget.get_admin_page_layout())
main_window_tab.addTab(admin_tab, "Admin")
main_window_tab.addTab(tab1, "tab1")
main_window_tab.addTab(tab2, "tab2")
main_window_tab.addTab(tab3, "tab3")
main_window_tab.addTab(tab4, "tab4")
main_window_tab.addTab(tab5, "tab5")
main_window_tab.addTab(tab6, "tab6")
main_window_tab.addTab(tab7, "tab7")
main_window_tab.show()
QtGui.QShortcut(QtGui.QKeySequence('Ctrl+Q'), main_window_tab, exit_application)
sys.exit(app.exec_())
The idea is to set the QStackedWidget with the Qt::AlignCenter alignment in the layout so it changes:
self.admin_page_layout.addWidget(self.admin_page_switch, 0, 0)
to:
self.admin_page_layout.addWidget(self.admin_page_switch, 0, 0, alignment=QtCore.Qt.AlignCenter)
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys, os, time
import Queue
import threading
import subprocess
class LearnButton(QPushButton):
def __init__(self, title, test):
super(QPushButton, self).__init__()
self._title = title
self._test = test
self.setText(title)
self.clicked.connect(self.click_threads)
self._q = Queue.Queue()
self.flag = True
def click_threads(self):
self.thread1 = threading.Thread(target=self.fun1)
self.thread2 = threading.Thread(target=self.fun2)
self.thread1.start()
self.thread2.start()
def fun1(self):
print "Val", self._test, self._title, type(self._test), type(self._title)
if self._test != "None":
self.date_time_string = time.strftime("%Y%m%d_%H%M%S")
self.retainedv = self.date_time_string
print self.date_time_string
self.flag = False
else:
print self.retainedv
def fun2(self):
print "Val", self._test, self._title, type(self._test), type(self._title)
self.setEnabled(False)
if self._test != "None":
while self.thread1.isAlive():
self.setText('h')
time.sleep(0.5)
self.setText('i')
time.sleep(0.5)
self.setText('i')
time.sleep(0.5)
self.setEnabled(True)
self.setText(self._title)
else:
self.setEnabled(True)
class LearnApp(QDialog):
def __init__(self):
super(QDialog, self).__init__()
self.setWindowTitle("LearnApp")
self.active = False
close_button = QPushButton("Close")
close_button.clicked.connect(self.close)
self.button1 = LearnButton("B1", "Im in B1")
self.button2 = LearnButton("B2", "Im in B2")
self.button3 = LearnButton("B3", "Im in B3")
self.check_button = LearnButton("Check", "None")
self.test_report = QTextEdit()
self.test_report.setReadOnly(True)
layout = QHBoxLayout()
sub_layout = QVBoxLayout()
sub_layout.addWidget(self.button1)
sub_layout.addWidget(self.button2)
sub_layout.addWidget(self.button3)
sub_layout.addWidget(self.check_button)
sub_layout.addWidget(close_button)
layout.addLayout(sub_layout)
layout.addWidget(self.test_report)
self.setLayout(layout)
self.setFocus()
app = QApplication(sys.argv)
dialog = LearnApp()
dialog.show()
app.exec_()
This is the code I'm trying to modify. Theme is after pressing B1, B2 or B3, I want to write the value of date_time_string to the text block.
Value of date_time_string shouldn't be calculated at the time when we press 'Check'.
Pressiing B1, calculates the value of date_time_string and after that what I'm trying to do is clicking 'Check' and writing the value of 'date_time_string' from the previous click (that is when B1 was clicked) to the text box.
Is there any way to retain the value of date_time_string for the next click?
Thanks