how to create click of button in PYQT - button

I've been having some trouble with create click of buttons in PyQT.
when i create click of button as below , this picture can't save
cv.SetImageROI(image, (pt1[0],pt1[1],pt2[0] - pt1[0],int((pt2[1] - pt1[1]) * 1)))
if self.Button.click():
cv.SaveImage('example.jpg', image)
cv.ResetImageROI(image)

The problem in your code is that you are performing a programmatic click on the button calling QPushButton.click on the line if self.Button.click():, what you need to do is to connect the signal QPushButton.clicked to a proper slot on your code. Singals and Slots is the way Qt handle some significant events that may occur on the object. Here I'll drop you an example, hope it helps:
import PyQt4.QtGui as gui
#handler for the signal aka slot
def onClick(checked):
print checked #<- only used if the button is checkeable
print 'clicked'
app = gui.QApplication([])
button = gui.QPushButton()
button.setText('Click me!')
#connect the signal 'clicked' to the slot 'onClick'
button.clicked.connect(onClick)
#perform a programmatic click
button.click()
button.show()
app.exec_()
Note: To understand the underlying behavior read the docs of Qt/PyQt.

Related

confused by clicked() and clicked(bool) in qt 4 signal and slot

I am using qt 4.8.6 and visual studio 2008 to develop a project and confused by clicked() and clicked(bool). While building a connection for an object which will emit a signal:
connect(sender, SIGNAL(clicked(bool)), receiver, SLOT(myslot()));
will trigger myslot(); and
connect(sender, SIGNAL(clicked()), receiver, SLOT(myslot()));
will not trigger it. However, I find other many examples about connect which all use clicked() not clicked(bool). Why cannot I use clicked()?
I look through Qt Assistant about:
void QAbstractButton::clicked ( bool checked = false ) [signal]
This signal is emitted when the button is activated (i.e. pressed down then released while the mouse cursor is inside the button), when the shortcut key is typed, or when click() or animateClick() is called. Notably, this signal is not emitted if you call setDown(), setChecked() or toggle().
If the button is checkable, checked is true if the button is checked,
or false if the button is unchecked.
I cannot find its reason. At the same time, what are the differences of the "checked" and "unchecked"?
By the way, I build a connect by pressing the left mouse button and drag the cursor. Another way is to rightclick the object, then the context menu will applear "go to slot", but my Qt Designer(4.8.6) will not. How to deal with it?
3 quesions hope to get help. Many thanks in advance.
I'm not sure I really understand the question(s), but the reason you can't connect to a clicked() signal is because there is no such thing... the function profile is clearly clicked(bool) (see docs).
Qt will only show a runtime error when it can't connect signal/slot (qWarning to stderr), it is not obvious at compile-time. Try examining the program output for warnings.
Edit: removed misleading information.
I encountered the same phenomenon too.
I think clicked(bool) and clicked(bool = false) is different.
The signal has different events.
I guess your "myslot()" may trigger the second event.

Qt pass data between multiple forms

I am new to Qt and understands the concept of signal and slots. However I am not able to implement it.
My objective is:
Form1 has a button Config. So when I click Config it should open another form Form2( without closing Form1) and send a string strData to Form2.
In Form2 I set some value in the string strData. Then I click Ok button in Form2, Form2 should close and return back the string to Form1.
When the call returns back to Form1, it should continue from where it emitted the signal to invoke Form2.
Any help is highly appreciated.
You can't do this using signals/slots; the signal is emitted, and all of the connected slots are executed, and then the code continues from where the signal is emitted and eventually returns to the event loop. That's when your second form is actually shown and the user can respond to it, but by then, your code is long past where the signal was emitted.
What I believe you're looking for is the QDialog::exec method; use it in place of the signal. The basic pattern of the code is:
// This is the response to click on Config...
Form2Dialog form2;
form2.setSomeStringValue (some_value);
if (form2.exec() == QDialog::Accepted)
{
QString some_new_value = form2.newValue();
}
The Form2Dialog is a subclass of QDialog where you've added your own setSomeStringValue and newValue methods. (What you actually name these is up to you.)
The important thing is that the exec method blocks and doesn't return until the user selects OK or Cancel on the dialog, or closes it using the "close" button in the title bar (if there is one).

QTabWidget: close tab button not working

I have set ui->tabWidget->setTabsClosable(true); but QTabwidget only showing a cross on each tab that is not closing tab on click on this button. What else I have to do to make tabs closable? I tried to connect any slot (which would be proper for this work) of close to signal tabCloseRequested(int) but couldn't find any such slot in tabwidget. Please suggest the right way.
Create a slot e.g. closeMyTab(int) and connect the tab widget's tabCloseRequested(int) signal to this slot. In this slot call tab widget's removeTab method with the index received from the signal.
See this answer for more details.
For future stumblers upon this question looking for a PyQt5 solution, this can be condensed into a 1-liner:
tabs = QTabWidget()
tabs.tabCloseRequested.connect(lambda index: tabs.removeTab(index))
The tabCloseRequested signal emits an integer equal to the index of the tab that emitted it, so you can just connect it to a lambda function that takes the index as its argument.
The only problem I could see with this is that connecting a lambda function to the slot prevents the object from getting garbage collected when the tab is deleted (see here).
EDIT (9/7/21): The lambda function isn't actually necessary since QTabWidget.removeTab takes an integer index as its sole argument by default, so the following will suffice (and avoids the garbage-collection issue):
tabs.tabCloseRequested.connect(tabs.removeTab)
The best way to do it since we got new connection syntax (Qt 5) is:
QTabWidget* tabWidet = new QTabWidget();
connect(tabWidget->tabBar(), &QTabBar::tabCloseRequested, tabWidget->tabBar(), &QTabBar::removeTab);
You just need to tell the tabWidget itself to close the requested tab index (the param passed to the slot) as this:
ui->tabWidget->removeTab(index);

Detecting enter on a QLineEdit or QPushButton

I've built an app for a game, simple to start. It's a game in which the system randomly chooses a number and a gamer (player) tries to find out the number. Everything is almost done. The app consists of a QLineEdit, a label and three buttons. Once the app tells the player the range of the wanted number, he/she types a bet_number and clicks on the play button. And according to this number he/she gets a message about how close or far the wanted number is away from the bet_number.
But I find it a little disgusting to click a button. Instead I want to use Enter key to play. So to achieve this, it comes down to specifically two questions:
How could one change to using Enter to play (I mean I need know when QLineEdit detects enter key is pressed)? In this way I'll code properly to point the play method.
If the play button's got the focus, how do you use enter key on this button? (make Button accept Enter key)
For the QLineEdit connect to the returnPressed signal.
Alternatively, if you use the setAutoDefault method on your QPushButtons you emit the clicked signal when Enter is pressed on a focused QPushButton:
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import sip
sip.setapi('QString', 2)
sip.setapi('QVariant', 2)
from PyQt4 import QtGui, QtCore
class MyWindow(QtGui.QWidget):
def __init__(self, parent=None):
super(MyWindow, self).__init__(parent)
self.pushButtonOK = QtGui.QPushButton(self)
self.pushButtonOK.setText("OK")
self.pushButtonOK.clicked.connect(self.on_pushButtonOK_clicked)
self.pushButtonOK.setAutoDefault(True)
self.lineEditNumber = QtGui.QLineEdit(self)
self.lineEditNumber.returnPressed.connect(self.pushButtonOK.click)
self.layoutHorizontal = QtGui.QHBoxLayout(self)
self.layoutHorizontal.addWidget(self.pushButtonOK)
self.layoutHorizontal.addWidget(self.lineEditNumber)
#QtCore.pyqtSlot()
def on_pushButtonOK_clicked(self):
inputNumber = self.lineEditNumber.text()
if inputNumber.isdigit():
info = "You selected `{0}`"
else:
info = "Please select a number, `{0}` isn't valid!"
print info.format(inputNumber)
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
app.setApplicationName('MyWindow')
main = MyWindow()
main.show()
sys.exit(app.exec_())
QLineEdit will emit the signal returnPressed() whenever the user presses the enter key while in it: http://qt-project.org/doc/qt-4.8/qlineedit.html#signals. You can either connect this signal to your button's click() slot or directly call whatever your button's clicked() signal was connected to.
A slight C++ variation on other answers, it's not significantly different, but I thought i would include it anyway because how you lay things in QT code can be very different from codebase to codebase and I wanted to strip out the extraneous stuff to give the shortest and easiest to understand excerpt of code.
QLineEdit *TextSend = new QLineEdit("");
QPushButton *SendPB = new QPushButton("Send!");
connect(TextSend, &QLineEdit::returnPressed, this, &CLITab::SendCommand);
connect(SendPB, &QPushButton::released, this, &CLITab::SendCommand);
So what this is doing is we create a QLineEdit textbox and a QPushbutton.
We do cosmetic things like set the string label for them and add them to our layout.
Then we setup a callback handler, which will be triggered when the QLineEdit returns "returnPressed", which then calls automatically into a function which i wrote called "CLITab::SendCommand()", and then it's upto this function to extract the data out of QLineEdit and do whatever needs to be done. In practice the TextSend and SendPB pointers would live in the parent class, so that SendCommand() has visibility over these objects.
Just putting this here, along side an example pushbutton, because essentially they work in precisely the same way, all that's different is the signal name emitted.

QT signals & slots

How to use signal and slots for handling events i.e when a pushButton is clicked some number should be displayed in QLineEdit.Just like in caluculator application when a number is clicked the corresponding is displayed .
connect a widget's signal to other's widget slot.
Signal = Emitted when the button (for instance) is pressed.
Slot = called when a certain singal is fired, and this signal is connected to this slot.
If You use QtCreator here is the procedure:
right click on the pushbutton. Select go to slot.
Select clicked()
QtCreator will open C++ editor with new empty member function defined that implements
your slot. This function will be called whenever someone clicks this button.
Now in this function you can call method of another widget ot modify its contants.
This book is quite good for starters:
http://www.amazon.com/Book-Qt-Art-Building-Applications/dp/1593271476/ref=sr_1_8?ie=UTF8&qid=1300905855&sr=8-8
Good luck.

Resources