In a widget I put two QPushButton (let's say "OK" at left and "EXIT" at right).
They regularly work when I press them using the mouse.
Suppose I want to switch from one to the other using TAB key: is it possible?
And how can do this?
On some platforms, keyboard focus navigation among buttons is a default behavior, but on some it isn't.
If you wish keyboard navigation on all platforms, the buttons should have a Qt::StrongFocus policy set on them. Note that the shortcut used to trigger the buttons is also platform-specific. E.g. on OS X you'd use Space.
#include <QtWidgets>
int main(int argc, char ** argv) {
QApplication app{argc, argv};
QWidget w;
QVBoxLayout layout{&w};
// Individual Buttons
QPushButton p1{"button1"}, p2{"button2"};
for (auto p : {&p1, &p2}) {
layout.addWidget(p);
p->setFocusPolicy(Qt::StrongFocus);
}
// A button box
QDialogButtonBox box;
for (auto text : {"button3", "button4"})
box.addButton(text, QDialogButtonBox::NoRole)->setFocusPolicy(Qt::StrongFocus);
layout.addWidget(&box);
w.show();
return app.exec();
}
I tried it out on KDE/Ubuntu. It works automatically.
main.cpp
#include <QApplication>
#include "mainwindow.hpp"
int main(int argc, char** args) {
QApplication app(argc, args);
MainWindow m;
m.show();
return app.exec();
}
mainwindow.hpp
#ifndef MAINWINDOW_HPP
#define MAINWINDOW_HPP
#include <QMainWindow>
class MainWindow : public QMainWindow {
Q_OBJECT
public:
MainWindow();
};
#endif // MAINWINDOW_HPP
mainwindow.cpp
#include "mainwindow.hpp"
#include <QPushButton>
#include <QVBoxLayout>
MainWindow::MainWindow() : QMainWindow() {
auto* w = new QWidget;
auto* l = new QVBoxLayout;
auto* p1 = new QPushButton("ok");
auto* p2 = new QPushButton("exit");
l->addWidget(p1);
l->addWidget(p2);
w->setLayout(l);
setCentralWidget(w);
}
a.pro
TEMPLATE = app
TARGET = a
INCLUDEPATH += .
QT += widgets
HEADERS += mainwindow.hpp
SOURCES += main.cpp mainwindow.cpp
QMAKE_CXXFLAGS += -std=c++14
Edit: Apparently the buttons switch focus, but pressing enter does nothing. I guess you have to use focus-related mechanics (search for "focus" in the QWidget documentation) and implement it yourself. Or have a look at QDialog (as a replacement for QMainWindow in my example). It should have some meaningful default behavior for the enter and escape buttons.
Side note: Maybe you rather want to use the QDialogButtonBox for ok- and exit-buttons in your project. It's the cross-platform way of displaying OK/Cancel/Accept/Reject/... buttons because their arrangement differs between platforms. And this class can help you with that.
It is easier than all that code. Just use setFocusPolicy with Tabfocus on both buttons like this:
yourButtonOk->setFocusPolicy(Qt::TabFocus);
yourButtonExit->setFocusPolicy(Qt::TabFocus);
Related
I'm doing the Udemy C++ Qt tutorial. The idea is to have a QPushButton button in a window.
When I run this, I get an empty window. Using Qt 5.5 in Win7.
Here are my files:
main.cpp
#include<QApplication>
#include"S_S.h"
int main(int argc, char *argv[])
{
QApplication app(argc,argv);
S_S MyTest;
MyTest.show();
return app.exec();
}
S_S.h
#ifndef S_S_H
#define S_S_H
#include<QApplication>
#include<QWidget>
#include<QPushButton>
class S_S : public QWidget
{
public:
S_S();
private:
QPushButton *Button1;
};
#endif // S_S_H
S_S.cpp
#include"s_s.h"
S_S::S_S():QWidget()
{
Button1=new QPushButton;
Button1->setText("Cancel");
connect(Button1,SIGNAL(clicked()),qApp,SLOT(quit()));
}
You probably want to construct the QPushButton and pass in a parent widget:
Button1 = new QPushButton(this);
I assume you want the S_S instance to be the parent.
You might also want to set the size and location of the button:
Button1->setGeometry(QRect(QPoint(100, 100), QSize(200, 50)));
There is an example here of using QPushButton.
When using a QToolButton and the setDefaultAction(myAction) method, it will get the default actions properties
Reference:
If a tool button has a default action, the action defines the button's
properties like text, icon, tool tip, etc.
So I try to overwrite the icon, calling setIcon on the QToolButton.
myAction.setIcon(...);
myToolButton->setDefaultAction(myAction);
myToolButton->setIcon(...);
But it myToolButton still has the Icon of myAction.
Is there a way to hold the default action but overwrite it's icon, only for the QToolButton, not for the action itself? In otherwords: How can the QToolButtons have different properties than its default action?
If you take a look at the source for QToolButton::setDefaultAction(QAction* action), it uses setIcon(action->icon()) to set the icon from the action you give it. You can override that icon manually by calling setIcon with your desired separate icon after you call setDefaultAction.
Edit:
Here's a quick example you can try. Maybe you can compare it to what you're currently doing or post an example of your own?
MainWindow.cpp
#include "MainWindow.hpp"
#include <QAction>
#include <QToolButton>
MainWindow::MainWindow(QWidget* parent) :
QMainWindow(parent) {
QAction* action = new QAction(QIcon(QStringLiteral("original.jpg")), QStringLiteral("Test Action"), this);
QToolButton* toolButton = new QToolButton(this);
toolButton->setDefaultAction(action);
toolButton->setIcon(QIcon(QStringLiteral("new.jpg")));
}
MainWindow.hpp
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QWidget>
class MainWindow : public QMainWindow {
Q_OBJECT
public:
explicit MainWindow(QWidget* parent = nullptr);
};
#endif // MAINWINDOW_H
main.cpp
#include "MainWindow.hpp"
#include <QApplication>
int main(int argc, char* argv[]) {
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
QToolButton icon will reset to action icon when action changed.
We need re-override code like this;
connect(toolButton, &QAction::changed, [=](){
toolButton->setIcon(QIcon(QStringLiteral("new.jpg")));
});
I am a newbie in Qt-programming. I have read a book about GUI-programming with Qt. I have an trouble in creating a dialog. Here is sample code:
// gotocell.h
#ifndef GOTOCELL_H
#define GOTOCELL_H
#include <QDialog>
#include <QtWidgets>
#include "ui_gotocell.h"
class GoToCellDialog : public QDialog, public Ui::GoToCellDialog
{
Q_OBJECT
public:
GoToCellDialog (QWidget *parent = 0);
private slots:
void on_lineEdit_textChanged();
};
#endif // GOTOCELL_H
// gotocell.cpp
#include <QtWidgets>
#include "gotocell.h"
#include <QtWidgets>
GoToCellDialog::GoToCellDialog (QWidget *parent):
QDialog (parent)
{
setupUi(this);
QRegExp regExp ("[A-Za-z][1-9][0-9]{0,2}");
lineEdit->setValidator(new QRegExpValidator(regExp, this));
connect (okButton, SIGNAL(clicked()), this, SLOT(accept()));
connect (cancelButton, SIGNAL(clicked()), this, SLOT(reject()));
}
void GoToCellDialog::on_lineEdit_textChanged()
{
okButton->setEnabled(lineEdit->hasAcceptableInput());
}
// main.cpp
#include "gotocell.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
GoToCellDialog *dialog = new GoToCellDialog;
dialog->show();
return a.exec();
}
but when I compiled, there is an error: no known conversion for argument 1 from 'GoToCellDialog* const' to 'QMainWindow*'at setupUi() function. I think because the designer in Qt Creator created a QMainWindow, not a QDialog. So I changed GoToCellDialog class to QMainWindow. But there is no slots whose name is "accepted", "rejected" in QMainWindow. Can anyone help me?
If you want to display a Dialog as main window you have two choices:
1. make the whole main window QDialog based
2. design the Dialog separately and set it as the main windows central Widget (QMainWindow->setCentralWidget()).
In both cases you still have the problem what semantics you give to the OK and Cancel buttons. Generally it may be a better idea to consider what the main window of the application should contain, and design the dialogs later.
I want to show some database row values with radio button selection in Qt GUI. How this can be accomplished?. This could be done using foreach loop I guess. I have studied a bit about the following classes :
1) QMainWindow
2) QSqlTableModel
3) QTableWidget.
But which one satisfies my requirement? I am not able to implement it, please guide me. Thanks in advance.
I have implemented upto this in my source file-
main.cpp:
#include <QtGui/QApplication>
#include <QtSql>
#include <QTableWidget>
#include <QMessageBox>
#include "mainwindow.h"
#include <QRadioButton>
#include <QVBoxLayout>
#include <QGroupBox>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QTableWidget* table = new QTableWidget();
table->setWindowTitle("Connect to Mysql Database Example");
QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
db.setHostName("localhost");
db.setDatabaseName("guests");
db.setUserName("sri");
db.setPassword("******");
if (!db.open())
{
QMessageBox::critical(0, QObject::tr("Database Error"),
db.lastError().text());
}
QSqlQuery query("SELECT * FROM new_members");
table->setColumnCount(query.record().count());
table->setRowCount(query.size());
int index=0;
while (query.next())
{
table->setItem(index,0,new QTableWidgetItem(query.value(0).toString()));
table->setItem(index,1,new QTableWidgetItem(query.value(1).toString()));
index++;
}
// This is sample radiobutton from QGroupBox class. Like this I need to implement the values from DB in with radio button selections for each value
QMainWindow *window = new QMainWindow();
window->setWindowTitle(QString::fromUtf8("QGroupBox"));
window->resize(400, 400);
QGroupBox *groupBox = new QGroupBox("Radio Buttons");
QRadioButton *radio1 = new QRadioButton("Radio button 1");
radio1->setChecked(true);
QVBoxLayout *vbox = new QVBoxLayout;
vbox->addWidget(radio1);
groupBox->setLayout(vbox);
window->setCentralWidget(groupBox);
window->show();
table->show();
//MainWindow w; w.show();
return a.exec();
}
Use a QSqlTableModel to drive a QTableView, you will need a custom QStyledItemDelegate to draw the QRadioButton (yes I said draw, and not create), and create an editor widget (of course that really will be a QRadioButton).
This is quite a big job, so you will need to read the above class' docs to reimplement the bits you need. Start with the MVC documents.
I am trying to implement a input method with Qt Embedded.
There is a lookup table for choosing the candidate words for typing. "text input area" to the "lookup table" and the selected word cannot be sent to the "text input area".
Dose anyone have any idea to solve this problem? Thanks~
Here I give a simple example:
main.cpp
#include "InputWidget.h"
#include "ButtonWidget.h"
#include <QApplication>
int main(int argc,char *argv[])
{
QApplication app(argc,argv);
InputWidget *inputWidget=new InputWidget();
ButtonWidget *buttonWidget=new ButtonWidget();
inputWidget->show();
buttonWidget->show();
int ref=app.exec();
inputWidget->deleteLater();
buttonWidget->deleteLater();
return ref;
}
InputWidget.h
#include <QWidget>
#include <QPlainTextEdit>
#ifndef _InputWidget_H_
#define _InputWidget_H_
class InputWidget:public QWidget
{
Q_OBJECT
public:
InputWidget(QWidget *parent=0);
private:
QPlainTextEdit *inputArea;
};
#endif
InputWidget.cpp
#include "InputWidget.h"
#include <QPushButton>
#include <QVBoxLayout>
InputWidget::InputWidget(QWidget *parent):QWidget(parent)
{
//input area setup
inputArea=new QPlainTextEdit(this);
//main layout
QVBoxLayout *mainLayout=new QVBoxLayout(this);
mainLayout->setContentsMargins(1,4,1,1);
mainLayout->addWidget(inputArea);
setLayout(mainLayout);
}
ButtonWidget.h
#include <QWidget>
#include <QPushButton>
#ifndef _ButtonWidget_H_
#define _ButtonWidget_H_
class ButtonWidget:public QWidget
{
Q_OBJECT
public:
ButtonWidget(QWidget *parent=0);
private:
QPushButton *selectedBtn;
public slots:
void changeBtnText();
};
#endif
ButtonWidget.cpp
#include "ButtonWidget.h"
#include <QPushButton>
#include <QVBoxLayout>
ButtonWidget::ButtonWidget(QWidget *parent):QWidget(parent)
{
//selectedBtn setup
selectedBtn=new QPushButton(tr("Click Me!!"),this);
connect(selectedBtn,SIGNAL(clicked()),this,SLOT(changeBtnText()));
//main layout
QVBoxLayout *mainLayout=new QVBoxLayout(this);
mainLayout->setContentsMargins(1,4,1,1);
mainLayout->addWidget(selectedBtn);
setLayout(mainLayout);
}
void
ButtonWidget::changeBtnText()
{
selectedBtn->setText("I am clicked :)");
}
Those codes would generate a widget which has a PlainTextEdit "inputArea" and a widget which has a PushButton "selectedBtn".
First, I input some words in the "inputArea". The current foucs is on "inputArea" in the InputWidget.
But when I move mouse to ButtonWidget and click the "selectedBtn", the foucs is changed to "selectedBtn" in the ButtonWidget.
How do I click the "selectedBtn" but still keep the foucs on "inputArea"? Thanks~
Just like my comment described in laura's answer, InputWidget and ButtonWidget may have no identical parent and I cannot use QWidget's "setFocus" slot to change the current focus between them.
First of all, you will need to make the two widgets know about each other. Once you have done that (by setting the text widget into the button widget or by adding them both to the same parent widget), you can try to see if QWidget's setFocus slot can help you (look at the other slots too, some might be useful for this).
Perhaps implement something like this, in the ButtonWidget:
(in the header) declare a signal foo()
(in the constructor) connect button widget's foo signal to InputWidget's setFocus slot
(in the changeBtnText) after you've done everything you wanted, emit foo()
Note though that setFocus works if the window is active.
You might be able to get what you want by playing with the focusPolicy for your widget. Pay attention to the Qt::NoFocus option. I don't think it prevents mouse clicks on your widget, but you'll want to test to be sure.
Thank laura and cjhuitt, your responses give me a big hint to solve my question.
Because InputWidget and ButtonWidget are two independent widgets, if we want to deal with the focus issue between them, we need a "global" control, i.e., use QApplication to do the focus job.
The key point is using QApplication's "focusChanged" slot and QWidget's "activateWindow". The following is my modification.
main.cpp
#include "InputWidget.h"
#include "ButtonWidget.h"
#include <QApplication>
int main(int argc,char *argv[])
{
QApplication app(argc,argv);
InputWidget *inputWidget=new InputWidget();
ButtonWidget *buttonWidget=new ButtonWidget(0,&app);
inputWidget->show();
buttonWidget->show();
int ref=app.exec();
inputWidget->deleteLater();
buttonWidget->deleteLater();
return ref;
}
ButtonWidget.h
#include <QWidget>
#include <QPushButton>
#include <QApplication>
#ifndef _ButtonWidget_H_
#define _ButtonWidget_H_
class ButtonWidget:public QWidget
{
Q_OBJECT
public:
ButtonWidget(QWidget *parent=0,QApplication *app=0);
private:
QPushButton *selectedBtn;
public slots:
void changeBtnText();
void changeFocus(QWidget *oldWidget,QWidget *curWidget);
};
#endif
ButtonWidget.cpp
#include "ButtonWidget.h"
#include <QPushButton>
#include <QVBoxLayout>
ButtonWidget::ButtonWidget(QWidget *parent,QApplication *app):QWidget(parent)
{
//selectedBtn setup
selectedBtn=new QPushButton(tr("Click Me!!"),this);
connect(selectedBtn,SIGNAL(clicked()),this,SLOT(changeBtnText()));
//main layout
QVBoxLayout *mainLayout=new QVBoxLayout(this);
mainLayout->setContentsMargins(1,4,1,1);
mainLayout->addWidget(selectedBtn);
setLayout(mainLayout);
//deal with focus
connect(app,SIGNAL(focusChanged(QWidget*,QWidget*)),this,SLOT(changeFocus(QWidget*,QWidget*)));
}
void
ButtonWidget::changeBtnText()
{
selectedBtn->setText("I am clicked :)");
}
void
ButtonWidget::changeFocus(QWidget *oldWidget,QWidget *curWidget)
{
if(oldWidget && curWidget==this)
oldWidget->activateWindow();
}
InputWidget.cpp and InputWidget are not modified.
This solution can work in this example, but I am not sure that it can work in two independent Qt programs(they have their own QApplication), especially in Qt Embedded environment. I would continue doing some tests on it. If there are any results, I would also post them here.
Thank for this discussion, I have learned a lot and thank you all again!!